As I continue my efforts to get my Android applications under unit and integration tests, I have come across a few tips/tricks to successfully deal with troublesome code. So I decided to start a new blog post series, “Testing Tricks”. I will try to post a new trick each week. So let’s get started…
Problem Code
I wanted to test this code:
public void readDeepLink(String path) { new DeepLinkReader().readDeepLink(path); }
Just wanted to make sure the readDeepLink method was being called. The troublesome part is that I didn’t want to create a actual DeepLinkReader because the real readDeepLink method made calls to the network. So what’s the fix?
Solution
Wrap the call to the “new” creation in a separate method. That way I could override the newly created method with a mock. This would avoid creating a real DeepLinkReader object and would allow me to use Mockito to verify the mock’s interactions.
Fixed Code
// in the MainPresenter.java public void readDeepLink(String path) { getDeepLinkReader().readDeepLink(path); } DeepLinkReader getDeepLinkReader() { return new DeepLinkReader(currentData, events); }
// in the MainPresenterTest.java @Mock private DeepLinkReader deepLinkReader; @Test public void shouldReadDeepLink() throws Exception { MainPresenter mainPresenter = new MainPresenter() { DeepLinkReader getDeepLinkReader() { return deepLinkReader; } }; mainPresenter.readDeepLink("washingtonpost.com"); verify(deepLinkReader).readDeepLink("washingtonpost.com"); }
Hope you found this useful, until next time!