2014-04-10 23 views
0

测试用例有什么问题?不同的响应代码 - 内部测试不可接受的状态

我有以下代码:

@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":"[email protected]_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\":\"[email protected]_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

解决方法很简单,我想通过ContentNegotiationManagerFactoryBean需要.json后缀。正确的url应该是这样的:/register.json

0

我不相信MockMvcRequestBuilder增加如果不指定任何,则隐含地显示Accept标头。您应该添加一个

mockMvc.perform(post("/register") 
     .accept(MediaType.APPLICATION_JSON) 
     .contentType(MediaType.APPLICATION_JSON) 
     .content(s)) 
    .andExpect(status().isOk()); 
+0

Sory,它不能解决我的问题。响应仍然有状态'406'。 – user902691