I have a method in a class lets say doStuff which calls another method of another class execute:
@Component
class A {
@Autowired
B b;
int doStuff(){
return b.execute(1);
}
}
@Component
class B {
int execute(int i){
return i;
}
}
Now when I'm trying to mock the method execute, it is throwing nullPointer
@ExtendWith(MockitoExtension.class)
public class ATest{
@InjectMocks
A a;
@Mock
B b;
@Test
doStuffTest(){
when(b.execute(anyInt()).thenReturn(1);
assertEquals(1,a.doStuff());
}
}
It is throwing NullPointer Exception on line when(b.execute(anyInt()).thenReturn(1);
CodePudding user response:
@Autowired
annotation is part of Spring, while @Mock
is part of Mockito. @Autowired
will not be triggered using the Mockito test. Mocked class has to be a constructor where object can be injected by @InjectMock
.
If you want to use @Autowired
you need a Spring context like @SpringBootTest
or others that scan and configuration your project. So, if you would like to mock this bean, you will have to @MockBean
annotation.
CodePudding user response:
Issue resolved with @RunWith(MockitoJUnitRunner.class)
annotation, without that it's failing