【问题标题】:How do I autowire a field with a real implementation while mocking another field?如何在模拟另一个字段时自动连接具有真实实现的字段?
【发布时间】:2015-11-10 15:20:01
【问题描述】:

我正在尝试对 Spring-boot 控制器进行单元测试,而我的 @Autowired 字段之一返回为空。

我在这个控制器中有两个自动装配的字段:

public class UserProfileController{

@Autowired
private UserProfileService profileService;

@Autowired
private IDataValidator dataValidatorImpl;

我的测试类如下:

@RunWith(SpringJUnit4ClassRunner.class)
@WebIntegrationTest
@SpringApplicationConfiguration(classes = UserProfileServiceApplication.class)
public class ControllerTest {

private MockMvc mockMvc;

@Mock
UserProfileService profileServiceMock;

@Autowired
ApplicationContext actx;

@InjectMocks
private UserProfileController profileController;

@Before
public void setup() {
// Process mock annotations
String[] asdf = actx.getBeanDefinitionNames();
for (int i = 0; i < asdf.length; i++){
System.out.println(asdf[i]);
}

MockitoAnnotations.initMocks(this);

// Setup Spring test in standalone mode
this.mockMvc = MockMvcBuilders.standaloneSetup(profileController).build();

}

/**
* All this does is verify that we return the correct datatype and HTTP status
* @throws Exception
*/
@Test
public void testGetProfileSuccess() throws Exception {
Mockito.when(profileServiceMock.getProfile(Mockito.any(HashMap.class))).thenReturn(new HashMap<String, Object>());

mockMvc.perform(get("http://localhost:8095/UserName?tenantId=tenant1"))
.andExpect(status().isOk())
.andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8));

//verify profileService was only used once
Mockito.verify(profileServiceMock, Mockito.times(1)).getProfile(Mockito.any(HashMap.class));

//verify we're done interacting with profile service
Mockito.verifyNoMoreInteractions(profileServiceMock);
}

如果我在测试类中保持 IDataValidator 不变,它会出现 null 并且我得到 NPE。如果我@SpyDataValidatorImpl,它无法从 Spring 环境中找到它需要工作的属性。

我怎样才能让 IDataValidator 自动装配并维护它的 spring 环境上下文,就好像我只是在正常运行应用程序一样?

当我在 @Before setup() 方法中打印所有 bean 时,我可以在列表中看到 DataValidationImpl。

【问题讨论】:

  • 你在哪里嘲笑IDataValidator?
  • 我尽量不嘲笑它。当我使用 @spy 注释时,请参阅上面的编辑。

标签: junit spring-boot mockito


【解决方案1】:

当你用

模拟你的控制器时
MockMvcBuilders.standaloneSetup(profileController).build();

控制器在上下文中被替换。由于您没有在其中注入任何IDataValidator,因此它为空。

最简单的解决方案是将真正的IDataValidator 自动连接到您的测试类中,然后将其注入到控制器中。

在您的控制器中:

public class UserProfileController{

private UserProfileService profileService;
private IDataValidator dataValidatorImpl;

@Autowired
public UserProfileController(UserProfileService profileService, IDataValidator dataValidatorImpl) {
   this.profileService = profileService;
   this.dataValidatorImpl = dataValidatorImpl;
}

在你的测试中:

@RunWith(SpringJUnit4ClassRunner.class)
@WebIntegrationTest
@SpringApplicationConfiguration(classes = UserProfileServiceApplication.class)
public class ControllerTest {

private MockMvc mockMvc;

private UserProfileService profileService;

@Autowired
private IDataValidator dataValidator;

@Before
public void setup() {
    UserProfileService profileService = Mockito.mock(UserProfileService.class);
    UserProfileController controller = new UserProfileController(profileService, dataValidator);

   // Setup Spring test in standalone mode
   this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();

}

}

【讨论】:

    【解决方案2】:

    如果我理解正确,你想用真正的验证器和模拟服务注入UserProfileController。

    在这种情况下,我建议使用@ContextConfiguration annotaion,它允许在测试中配置上下文。您需要创建一个配置类:

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebIntegrationTest
    @SpringApplicationConfiguration(classes = UserProfileServiceApplication.class)
    public class ControllerTest {
    
    private MockMvc mockMvc;
    
    @Mock
    UserProfileService profileServiceMock;
    
    @Autowired
    ApplicationContext actx;
    
    //comment this line out
    //@InjectMocks
    @Autowired
    private UserProfileController profileController;
    
    @Before
    public void setup() {
    // Process mock annotations
    String[] asdf = actx.getBeanDefinitionNames();
    for (int i = 0; i < asdf.length; i++){
    System.out.println(asdf[i]);
    }
    
    //comment this line out
    //MockitoAnnotations.initMocks(this);
    
      @Configuration
      public static class Config {
    
        //wire validator - if it is not wired by other configurations
        @Bean
        Validator validator() {
            return new Validaor();
        }
    
        //wire mock service
        @Bean
        public UserProfileService profileService() {
            return mock(UserProfileService.class);
        }
    }
    

    【讨论】:

      【解决方案3】:

      好的,我发誓我是第一次这样做,但是在尝试重新创建为 jny 引发的错误时,它确实有效。

      我的解决方案是通过@Spy 注解注入并在我的@Before 设置方法中从ApplicationContext 获取bean。

      public class ControllerTest {
      
      private MockMvc mockMvc;
      
      @Mock
      UserProfileService profileServiceMock;
      
      @Spy
      IDataValidator dataValidator;
      
      @Autowired
      ApplicationContext actx;
      
      @InjectMocks
      private UserProfileController profileController;
      
      @Before
      public void setup() {
      
      dataValidator = (IDataValidator) actx.getBean("dataValidatorImpl");
      
      MockitoAnnotations.initMocks(this);
      
      // Setup Spring test in standalone mode
      this.mockMvc = MockMvcBuilders.standaloneSetup(profileController).build();
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-02
        • 1970-01-01
        相关资源
        最近更新 更多