Test fongo error in com.fasterxml.jackson.databind.JsonMappingException

0

I'm trying to perform a test through phon but I get the error:

  

com.fasterxml.jackson.databind.JsonMappingException: Can not   deserialize instance of com.formacion.pem.userProyect.User out of   START_ARRAY token at [Source:   [{"id": 1, "code": "1", "firstName": "Alice", "lastName": "Smith"}]; line:   1, column: 1]

Many gracais.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { ConfigServerWithFongoConfiguration.class }, properties = {
        "server.port=8980" }, webEnvironment = WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
@TestPropertySource(properties = { "spring.data.mongodb.database=test" })
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class UserControllerTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MockMvc mockMvc;

    private ObjectMapper jsonMapper;

    @Before
    public void setUp() {
        jsonMapper = new ObjectMapper();
    }

    @Test
    public void testGetUser() throws Exception {

        User userFongo = new User();
        userFongo.setId(1);
        userFongo.setCodigo("1");
        userFongo.setFirstName("Alice");
        userFongo.setLastName("Smith");
        mongoTemplate.createCollection("users");
        mongoTemplate.save(userFongo);

        ResultActions resultAction = mockMvc.perform(MockMvcRequestBuilders.get("http://localhost:8090/api/users"));
        resultAction.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
        MvcResult result = resultAction.andReturn();

        User userResponse = jsonMapper.readValue(result.getResponse().getContentAsString(), User.class);
        Assert.assertEquals(1, userResponse.getId());
        Assert.assertEquals("1", userResponse.getCodigo());
        Assert.assertEquals("Alice", userResponse.getFirstName());
        Assert.assertEquals("Smith", userResponse.getLastName());

    }
    
asked by alejandro Martinez Faci 27.12.2017 в 16:34
source

1 answer

0

The problem is that jsonMapper is waiting for an object and the JSON that you are passing is an array.

You can deserialize the JSON array to a Java array in the following way:

User[] userResponse = jsonMapper.readValue(result.getResponse().getContentAsString(), User[].class);
    
answered by 29.12.2017 / 10:02
source