我想單元測試一個Spring引導控制器,並且我的@Autowired
字段之一返回null。如何在嘲笑另一個字段的同時自動裝載真實實現的字段?
我在這個控制器配備了兩個自動連接字段:
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不變的測試類,它出現空和我得到一個NPE。如果我使用DataValidatorImpl,它無法從Spring環境中找到它需要工作的屬性。
我該如何讓IDataValidator自動裝載自身並維護它的彈簧環境上下文,就像我正常運行應用程序一樣?
當我在我的@Before
setup()方法中打印所有bean時,我可以在列表中看到DataValidationImpl。
你在哪裏嘲諷'IDataValidator'? – jny
我試圖不嘲笑它。當我使用'@ spy'註釋時,請參閱上面的編輯。 – lp1776