1
我想單元測試使用spring和mockito的其餘控制器。這是我的主控制器方法。使用mockMvc進行Spring JUnit測試
public static final String AUTHENTICATE_USER_URI = "/user/authenticate";
private static final Logger logger = LoggerFactory.getLogger(RestfulController.class);
@Autowired
User user;
@Autowired
AuthenticationService authService;
@CrossOrigin
@RequestMapping(value = (AUTHENTICATE_USER_URI), method = RequestMethod.GET, produces = "application/json")
private User getUserAuthenticationDetails(
@RequestParam("name") String name,
@RequestParam("password") String password) throws NamingException,
AuthenticationException {
boolean isAuth = true;
// checks user credentials
isAuth = authService.isAuthenticated(name, password);
if (isAuth) {
logger.debug("User is authenticated");
user = authService.getUserDetails(user, name);
// // persistUserInDB(user);
return user;
} else {
logger.debug("User is not authenticated");
return null;
}
}
這裏是我的JUnit測試:
@RunWith(MockitoJUnitRunner.class)
public class RestfulControllerTest {
private static final String AUTHENTICATE_USER_TEST_URI = "http://localhost:8086/LDAPAuthenticationApp/user/authenticate";
private MockMvc mockmvc;
@Mock
private AuthenticationService authService;
@Before
public void setUp() {
mockmvc = MockMvcBuilders.standaloneSetup(new RestfulController())
.setHandlerExceptionResolvers(exceptionResolver())
.setMessageConverters(messageConverters())
.build();
}
private MappingJackson2HttpMessageConverter messageConverters(){
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
return converter;
}
private HandlerExceptionResolver exceptionResolver() {
// exceptionResolver implementation here
}
// success test case
@Test
public void testGetUserAuthenticationDetails() throws Exception {
String[] name={"amol84","arpan","juhi"};
String value="pegasus84";
when(authService.isAuthenticated(any(String.class), any(String.class))).thenReturn(true);
when(authService.getUserDetails(any(User.class),any(String.class))).thenReturn(any(User.class));
for(int i=0;i<3;i++){
mockmvc.perform(get(AUTHENTICATE_USER_TEST_URI).param("name", name[i]).param("password", value))
.andDo(print()).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON));
}
verify(authService, atMost(3)).isAuthenticated(any(String.class), any(String.class));
}
在輸出響應,測試失敗,因爲它是獲得404錯誤,但它期待一個成功的200碼。我可以做錯什麼,因爲我相信我已經正確設置了獨立配置。爲什麼URI沒有正確映射到方法?請注意,它對應用程序前端的相同URI工作正常。下面是完整的URI進行適當的200響應我所用郵差工具,鉻測試:
http://localhost:8086/LDAPAuthenticationApp/user/authenticate?name=amol84&password=pegasus84
是的,這是工作..謝謝爲解決方案。 –