Reputation: 1965
I've been learning more about the Mockito framework within Java and I'm lost about what to do to complete this unit test.
Basically, the error from the console states that there is a NullPointerException when the Bar.sayHi() method is trying to be run from the Foo test. I suspect it has something to do with the autowired fields (but I maybe wrong)?
Below is a simple example of the problem that I'm running into:
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
@Mock
//@Spy // Cannot spy on an interface
IBar bar;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
// Given
FooImpl foo = new FooImpl();
foo.saySaySay();
// When
// Then
}
}
Here's the FooImpl class under testing (there's an interface for Foo):
public class FooImpl implements IFoo {
@Autowired
private IBar bar;
public void saySaySay() {
bar.sayHi();
}
}
And the Bar class (there's also an interface for Bar):
public class BarImpl implements IBar {
@Override
public void sayHi() {
System.out.println("hello");
}
}
Does anyone has a suggestion on this? Thanks.
Upvotes: 0
Views: 77
Reputation: 47608
RunWith(MockitoJUnitRunner.class)
public class FooTest {
@Mock
//@Spy // Cannot spy on an interface
IBar bar;
@InjectMocks
private FooImpl foo;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
// Given
foo.saySaySay();
verify(bar).sayHi();
// When
// Then
}
}
Upvotes: 0
Reputation: 3554
Just creating a mock of Ibar will not inject that mock into the @Autowired field. Autowiring is the job of Spring, not Mockito. You need to explicitly tell mockito to inject those into testing objects using @InjectMock
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
@InjectMocks
FooImpl foo;
@Mock
IBar bar;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
foo.saySaySay();
}
}
or manual set the mock object inside the tested object.
@Test
public void test() {
FooImpl foo = new FooImpl();
ReflectionTestUtils.setField(foo, "bar", bar);
foo.saySaySay();
}
Upvotes: 3