java.lang.AssertionError : Status expected:<200> but was:<400>

标签 java spring spring-mvc

这是我的 Controller ...

@RequestMapping(value = "/user", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, headers = "Accept=application/json")
public @ResponseBody ResponseMessage getUser(@RequestBody AvailableUser uuid) {
    logger.info("enter into getuser method's body");
    return Manager.availableUser(uuid);
}

这是我的测试 Controller ...

@Test 
public void testgetUser() throws Exception 
{
    AvailableUser availableUser=new AvailableUser();
    List<String> lst =new ArrayList<String>();
    lst.add("test1");
    lst.add("test2");
    availableUser.setUuId(lst);
    this.mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isCreated())
        .andExpect(status().isOk());
         when(Manager.availableUser(availableUser)).thenReturn(message);
}

我不知道 Controller 方法调用时如何传递对象("/user")表格testcontroller .

我收到错误消息 java.lang.AssertionError: Status expected:<200> but was:<400>

最佳答案

如果您使用 Jackson,最简单的方法是使用 ObjectMapper 实例将 AvailableUser 序列化为 JSON 字符串:

@Test 
public void testgetUser() throws Exception 
{
    // Same stuff
    ObjectMapper mapper = new ObjectMapper();
    this.mockMvc
        .perform(
                  post("/user")
                 .contentType(MediaType.APPLICATION_JSON)
                 .accept(MediaType.APPLICATION_JSON)
                 .content(mapper.writeValueAsString(availableUser))
        )
        .andExpect(status().isCreated())
        .andExpect(status().isOk());
    // Same as before
}

关于java.lang.AssertionError : Status expected:<200> but was:<400>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37115549/

相关文章:

java - 在 Android 中使用 POI 创建 Excel 文档后立即打开它们

java - 具有 Spring 配置类的静态资源

Java-Spring反射带来了类中不存在的方法

java - 在 Spring 中将服务 bean Autowiring 到 XML 定义的 bean 中

java - 带有 Java 11 : Unable to resolve persistence unit root URL 的 Spring Boot 2.1

java - 如何在 Java 中连接字符串数组

java - 无限循环数据库检查

java - ApplicationListener 与 ServletContextListener

java - 使用事务包装 Spring Security 自定义身份验证提供程序

spring - 如何找出 Spring 的 autowire 到底是什么?