Issue
I have this test in my Spring Boot app., but when I run the test, boniUserService is null
@RunWith(MockitoJUnitRunner.class)
public class BoniUserServiceTest {
private BoniUserService boniUserService;
@Test
public void getUserById() {
boniUserService.getUserById("ss");
}
}
Solution
The runner of your test that you specify with @RunWith
annotation specify who is going to process the annotation in your test class. They process the annotation in your test class and mock objects for you. In your case you have annotated your class with @RunWith(MockitoJUnitRunner.class)
So there should be some annotation of Mockito in your class to be processed by MockitoJUnitRunner
. To achieve your goal you can annotate your bean by @MockBean
annotation.
@RunWith(MockitoJUnitRunner.class)
public class BoniUserServiceTest {
@MockBean
private BoniUserService boniUserService;
@Test
public void getUserById() {
boniUserService.getUserById("ss");
}
}
Note that in this approach the Context of the Spring Application is not loaded. Usually you want to test one of your component based on mocked behavior of other components. So usually you achieve that like this:
@RunWith(SpringRunner.class)
@SpringBootTest
public class BoniUserServiceTest {
@Autowired
private BoniUserService boniUserService;
@MockBean
private BoniUserRepository boniUserRepository;
@Test
public void getUserById() {
given(this.boniUserRepository.getUserFromRepository()).willReturn(new BoinoUsr("test"));
boniUserService.getUserById("ss");
}
}
Answered By - Tashkhisi