laconicdev
laconicdev

Reputation: 6440

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?

Upvotes: 0

Views: 710

Answers (2)

VirtualTroll
VirtualTroll

Reputation: 3091

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.

Upvotes: 2

Pablo Aleman
Pablo Aleman

Reputation: 196

You should use

_sc.doSomething("abc");

not sc.doSomething("abc");

Upvotes: 2

Related Questions