测试用例有什么问题?
我有以下代码:
@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
With Body:
{
"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
答案 0 :(得分:0)
如果您未指定任何内容,我不相信MockMvcRequestBuilder
会隐式添加Accept
标头。你应该添加一个
mockMvc.perform(post("/register")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(s))
.andExpect(status().isOk());
答案 1 :(得分:0)
解决方案很简单,我想念.json
所需的ContentNegotiationManagerFactoryBean
后缀。正确的网址应如下所示:/register.json