Annyce Davis

ones and zeros

  • Home
  • Public Speaking
  • About Me
  • Courses
  • Life

Testing Tricks #1: Dealing with “new”

November 24, 2015 by Annyce Davis Leave a Comment

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 Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)

Related

Filed Under: Android Tagged With: Unit Testing

Follow Me

What engineering leaders need to know from this year’s Google I/O

I didn't intentionally aim to create a rhyming title, but there you have it. Each year, I look forward to Google I/O like a kid going back to school. This year … [Read More...]

Talk: The Real MVP

You have an idea for a new app. You've secured buy-in from the business. What's next? The MVP. But what does it take to ship a new app these days? What are the … [Read More...]

Categories

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

Copyright © 2023 · Beautiful Pro Theme on Genesis Framework · WordPress · Log in