测试用例有什么问题??
我有以下代码:
@PreAuthorize("permitAll()")
@RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public ModelMap register(@RequestBody @Valid User user, Locale locale, BindingResult result) {
logger.info("Register");
logger.info(user.getMail());
logger.info("usern " + user.getUsername());
logger.info("Result " + result.hasErrors());
if (result.hasErrors()) {
final Set<String> fieldsName = getErrorFieldsName(result);
throw new RegistrationException(fieldsName);
}
if (!isValidateMail(user.getMail()))
throw new RegistrationException(Collections.singleton("mail"));
final UUID id = UUID.randomUUID();
userRepo.saveUser(escapeUser(user, id));
return new ModelMap("msg", "You are registered correct!");
}
当我通过REST Client
调用此控制器时,如:
POST
请求标头
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: application/json
Accept: */*
DNT: 1
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pl,en;q=0.8,en-US;q=0.6
Cookie: JSESSIONID=yS__d1a5V8UOD6pF7qAeXfGmhfsacde
带机身:
{
"mail":"alddajdf@mad_kta.com",
"username":"User",
"password":"qwerdty123"
}
我收到带有以下标题的响应代码200
:
Connection: keep-alive
X-Powered-By: Undertow 1
Server: Wildfly 8
Transfer-Encoding: chunked
Content-Type: application/json
Date: Thu, 10 Apr 2014 16:27:42 GMT
但内部测试用例:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml")
public class RegisterAccountContrTest {
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
protected WebApplicationContext wac;
private MockMvc mockMvc;
@InjectMocks
private RegisterAccountContr contr;
@Before
public void init() {
this.mockMvc = webAppContextSetup(this.wac).build();
MockitoAnnotations.initMocks(this);
BasicConfigurator.configure();
}
@Test
public void testRegister() throws Exception {
final String s;
s = "{n" +
""mail":"alddajdf@mad_kta.com",n" +
""username":"User",n" +
""password":"qwerty123"n" +
"}";
mockMvc.perform(post("/register").contentType(MediaType.APPLICATION_JSON).content(s)).andExpect(status().isOk());
}
生成响应代码:
java.lang.AssertionError: Status
Expected :200
Actual :406
如果不指定MockMvcRequestBuilder
,我不认为它会隐式添加Accept
标头。你应该添加一个
mockMvc.perform(post("/register")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(s))
.andExpect(status().isOk());
解决方案很简单,我错过了ContentNegotiationManagerFactoryBean
所需的.json
后缀。正确的url应该是:/register.json