java.lang.AssertionError:响应内容

时间:2019-08-01 09:19:27

标签: java unit-testing spring-boot

我正在尝试测试UnitTest,但在运行测试时却得到java.lang.AssertionError: Response content
我的Logcat

java.lang.AssertionError: Response content
Expected: <[UserDTO [firstName=Ahmad, lastName=shahzad, userName=1, emailAddress=ahmad.shahzad@null], UserDTO [firstName=Jamshaid, lastName=iqbal, userName=2, emailAddress=jamshaid.ali@null], UserDTO [firstName=Waqas, lastName=Akram, userName=3, emailAddress=waqas.akram@null]]>
 but: was "[{\"firstName\":\"Ahmad\",\"lastName\":\"shahzad\",\"userName\":\"1\",\"emailAddress\":\"ahmad.shahzad@null\"},{\"firstName\":\"Jamshaid\",\"lastName\":\"iqbal\",\"userName\":\"2\",\"emailAddress\":\"jamshaid.ali@null\"},{\"firstName\":\"Waqas\",\"lastName\":\"Akram\",\"userName\":\"3\",\"emailAddress\":\"waqas.akram@null\"}]"
Expected :<[UserDTO [firstName=Ahmad, lastName=shahzad, userName=1, emailAddress=ahmad.shahzad@null], UserDTO [firstName=Jamshaid, lastName=iqbal, userName=2, emailAddress=jamshaid.ali@null], UserDTO [firstName=Waqas, lastName=Akram, userName=3, emailAddress=waqas.akram@null]]>
Actual   :"[{\"firstName\":\"Ahmad\",\"lastName\":\"shahzad\",\"userName\":\"1\",\"emailAddress\":\"ahmad.shahzad@null\"},{\"firstName\":\"Jamshaid\",\"lastName\":\"iqbal\",\"userName\":\"2\",\"emailAddress\":\"jamshaid.ali@null\"},{\"firstName\":\"Waqas\",\"lastName\":\"Akram\",\"userName\":\"3\",\"emailAddress\":\"waqas.akram@null\"}]"

at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$string$3(ContentResultMatchers.java:130)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)

UnitTestCase类

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UnitTestAuth {
@Autowired
public MockMvc mvc;

@Test
public void getHello() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/auth").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string(equalTo(new UserController().getUsers())));
}


}

控制器类

@RestController
@RequestMapping("/auth")
public class UserController {

private static final Logger LOGGER = Logger.getLogger(UserController.class.getName());

@Value("${mail.domain ?: google.com}")
private static String mailDomain;

private List<UserDTO> users = Arrays.asList(new UserDTO("Ahmad", "shahzad", "1", "ahmad.shahzad@" + mailDomain),
        new UserDTO("Jamshaid", "iqbal", "2", "jamshaid.ali@" + mailDomain),
        new UserDTO("Waqas", "Akram", "3", "waqas.akram@" + mailDomain));


@RequestMapping(method = RequestMethod.GET, headers = "Accept=application/json")
public List<UserDTO> getUsers() {
    return users;
}

@RequestMapping(value = "{userName}", method = RequestMethod.GET, headers = "Accept=application/json")
public UserDTO getUserByUserName(@PathVariable("userName") String userName) {
    UserDTO userDtoToReturn = null;
    for (UserDTO currentUser : users) {
        if (currentUser.getUserName().equalsIgnoreCase(userName)) {
            userDtoToReturn = currentUser;
            if (LOGGER.isLoggable(Level.INFO)) {
                LOGGER.info(String.format("Found matching user: %s", userDtoToReturn.toString()));
            }
            break;
        }
    }

    return userDtoToReturn;
}
}
  

问题:   我无法获取如何匹配这两个字符串才能通过测试。感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您正尝试将内容字符串与调用toString()方法时的实际对象进行比较,如下所示:

Expected: <[UserDTO [firstName=Ahmad, lastName=shahzad, userName=1, emailAddress=ahmad.shahzad@null], UserDTO [firstName=Jamshaid, lastName=iqbal, userName=2, emailAddress=jamshaid.ali@null], UserDTO [firstName=Waqas, lastName=Akram, userName=3, emailAddress=waqas.akram@null]]>
 but: was "[{\"firstName\":\"Ahmad\",\"lastName\":\"shahzad\",\"userName\":\"1\",\"emailAddress\":\"ahmad.shahzad@null\"},{\"firstName\":\"Jamshaid\",\"lastName\":\"iqbal\",\"userName\":\"2\",\"emailAddress\":\"jamshaid.ali@null\"},{\"firstName\":\"Waqas\",\"lastName\":\"Akram\",\"userName\":\"3\",\"emailAddress\":\"waqas.akram@null\"}]"

您必须解析内容中的每个属性,或使用某种JSON解析器来批量进行处理。然后将每个解析的属性与User对象的字段进行比较。

答案 1 :(得分:1)

在您的情况下,您需要使用json()而不是string(),因为您的响应会在内部转换为JSON。并使用ObjectMapper中的com.fasterxml.jackson.databind.ObjectMapper将您的响应列表转换为JSON。

@Test
public void getHello() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(new UserController().getUsers());
    mvc.perform(MockMvcRequestBuilders.get("/auth").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().json(result));
}

编辑:您可以使用ObjectMapper将对象列表转换为JSON。