Annyce Davis

Davis Technology Consulting

  • Home
  • About Me
  • Blog
  • Courses
  • Newsletter

Testing Tricks #1: Dealing with “new”

November 24, 2015 by Annyce Davis

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!

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on Bluesky (Opens in new window) Bluesky
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on Reddit (Opens in new window) Reddit

Related

Filed Under: Android Tagged With: Unit Testing

Follow Me

  • Bluesky

Categories

  • Android (60)
  • Career (5)
  • Communication (4)
  • Flutter (1)
  • Git (4)
  • Gradle (4)
  • Grails (23)
  • iOS (1)
  • Java (8)
  • JavaScript (6)
  • Kotlin (17)
  • Life (5)
  • Public Speaking (26)
  • Revenue (2)
  • RxJava (1)
  • Software Development (13)
  • Twitter (3)
  • Uncategorized (11)
  • Video Course (5)

Follow Me

  • Bluesky

Copyright © 2025 · All Rights Reserved · Log in