简体   繁体   English

使用 MockitoJUnitRunner 测试时的 null 服务

[英]null service when testing with MockitoJUnitRunner

I have this test in my Spring Boot app., but when I run the test, boniUserService is null我在我的 Spring 引导应用程序中进行了此测试,但是当我运行测试时,boniUserService 是 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.您使用@RunWith注释指定的测试运行器指定谁将处理您的测试 class 中的注释。他们处理您的测试 class 中的注释并为您模拟对象。 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 .在你的情况下,你已经用@RunWith(MockitoJUnitRunner.class)注释了你的 class 所以你的 class 中应该有一些注释 Mockito 由MockitoJUnitRunner处理。 To achieve your goal you can annotate your bean by @MockBean annotation.为了实现您的目标,您可以通过@MockBean注释来注释您的 bean。

@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.请注意,在这种方法中,不会加载 Spring 应用程序的上下文。 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.您需要启动应用程序上下文才能使其工作,这可以通过使用@SpringBootTest注释来实现,然后您需要使用@Autowired注释来注入您的服务。 Something like this:像这样:

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

    @Test
    public void getUserById() {

        boniUserService.getUserById("ss");

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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