简体   繁体   中英

null service when testing with MockitoJUnitRunner

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");
    
        }
    }

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");

    }
}

You need to have the application context up to make it work, it can be achieved by using the @SpringBootTest annotation, and then you need to inject your service using the @Autowired annotation. Something like this:

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class BoniUserServiceTest {
    
    @Autowired
    private BoniUserService boniUserService;
    

    @Test
    public void getUserById() {

        boniUserService.getUserById("ss");

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM