简体   繁体   中英

java.lang.AssertionError: Response content

I am trying to test a UnitTest but getting java.lang.AssertionError: Response content while running the test.
My 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 Class

@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())));
}


}

Controller Class

@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;
}
}

Problem: I am unable to get how should I match those both string in order to get the test passed. Thanks for your help.

You are trying to compare the content string with an actual object as it is when its toString() method is invoked as seen here:

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\"}]"

You have to parse each of the attributes in the content or use some kind of JSON parser to do it in bulk. Then compare each of the parsed attributes with the field of the User object.

You need to use json() instead of string() in your case as your response is converted to JSON internally. And use ObjectMapper from com.fasterxml.jackson.databind.ObjectMapper to convert your response list to 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));
}

EDIT : You can convert the List of objects to JSON using ObjectMapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM