【发布时间】: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