简体   繁体   中英

Unit testing a class that calls out to external service

I have the following class:

public class SomeClass {

    private Dependency dependency;

    public SomeClass(Dependency dep){
        this.dependency = dep;
    }


    public void doSomething(String s){
        Foo f = dependency.getFoo(s);
        f.doWork(); // fails because f is null
    }
}

I am trying to write a unit tests that will cover the doSomething method in which getFoo is an external call that I am trying to mock as follows:

@Mock
private Dependency dep;

@InjectMocks
private SomeClass _sc;


@Test
public void testSimple() {

Foo ff = new Foo();

when(dep.getFoo("abc")).thenReturn(ff);


SomeClass sc = new SomeClass();

sc.doSomething("abc"); // fails on null pointer exception

}

Unfortunately, I am getting a null reference exception in my unit test - since the mock class isn't being returned. How can I fix it?

You should use

_sc.doSomething("abc");

not sc.doSomething("abc");

First make sure your test class is annotated with MockitoJUnitRunner.

@RunWith(MockitoJUnitRunner.class)

Second, in your test, you should use your target test class "_sc" which gets injected with the mocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM