Reputation: 3
I have a class:
public abstract class Foo{
@Inject
private FooBarClient foobarclient;
public abstract long dofoo1();
public abstract long dofoo2();
public void doBar1(){
foobarClient.docall(faa);
}
}
I'd like to test the doBar1() method so I made my test class like this:
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
private Foo foo;
@Mock
private FoobarClient foobarClient;
@Before
public void init() {
foo = new Foo() {
dofoo1(){};
};
}
@Test
public void testControleValiditeSite() throws Exception {
// G
Response response=....;
Mockito.when(foobarClient.docall(Mockito.any(faa.class))).thenReturn(
response);
// W
foo.doBar1();
// T;
}
But I got a null pointer exception on the fooBarclient in doBar1().
I also tried to mock the abstract with:
Foo foo = Mockito.mock(Foo,Mockito.CALLS_REAL_METHODS);
Is there a better method to do this test?
EDIT :
I used reflection. Now the code looks like:
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
private Foo foo;
@Mock
private FoobarClient mockedFoobarClient;
@Before
public void init() {
foo = new Foo() {
dofoo1(){};
};
**MockitoAnnotations.initMocks(this);**
**ReflectionTestUtils.setField(foo , "foobarClient", mockedFoobarClient);**
}
@Test
public void testControleValiditeSite() throws Exception {
// G
Response response=....;
Mockito.when(foobarClient.docall(Mockito.any(faa.class))).thenReturn(
response);
// W
foo.doBar1();
// T;
}
Upvotes: 0
Views: 437
Reputation: 7267
You might not need to mock it, just create an instance in your test (assuming you're able to change the access type of client from private
to protected
).
Foo foo = new Foo() {
@Override
public long dofoo1() {
return 0;
}
@Override
public long dofoo2() {
return 0;
}
public void setClient(FooBarClient client) {
foobarclient = client;
}
};
foo.setClient(client);
foo.doBar1();
Upvotes: 1
Reputation: 32949
In your test class, create a non-abstract inner class that extends Foo
. Use that in your test.
Upvotes: 0