object to json , json to object for controller integration testing


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

public class TestsHelper {

public static String getJsonString(Object object) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper.writeValueAsString(object);
}

public static <T> T getObjectFromJson(String json, Class<T> type) throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper.readValue(json, type);
}
}

use case in testing class :
private OfficePhoto requestObject;
private OfficePhoto responseObject;
private String requestBody;
private String responseBody;

requestObject = new OfficePhoto();
defining another properties for requestObject
responseObject = new OfficePhoto();
defining another properties for responseObject

converting object to json string
requestBody = TestsHelper.getJsonString(requestObject);
responseBody = TestsHelper.getJsonString(responseObject);
using case: we returning responseBody object as json string
mockMvc.perform(get("/api/companies/1/offices/1/photos/1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().json(responseBody));

Comments

Popular posts from this blog

Installation instructions for some programs on linux ubuntu

Hibernate and Application Performance

timezone ile bagli Jackson deserializableda problem