【发布时间】:2021-05-12 23:44:09
【问题描述】:
我正在尝试运行下一个测试:
@WebMvcTest(TuCasitaController.class)
class TuCasitaControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private TuCasitaService tuCasitaService;
ObjectMapper objectMapper;
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
}
@Test
public void testGetInfoHouse() throws Exception {
/* Given */
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
String houseCorrect = ow.writeValueAsString(InfoTestGenerator.generatesCorrectTestInfo());
String expected = ow.writeValueAsString(InfoTestGenerator.generateValidResponse());
System.out.println(expected);
/* When */
mvc.perform(post("/info")
.contentType(MediaType.APPLICATION_JSON)
.content(houseCorrect))
/* Then */
.andExpect(status().isOk())
.andExpect(content().json(expected));
}
}
但它会在.andExpect(content().json(expected)) 行抛出 org.json.JSONException "Unparsable JSON string"。这是我要解析的对象:
public static Response generateValidResponse(){
RoomArea room1 = RoomArea.builder().roomName("Recamara Principal").area(25).build();
RoomArea room2 = RoomArea.builder().roomName("Recamara Daniel").area(28).build();
RoomArea room3 = RoomArea.builder().roomName("Recamara Julieta").area(25).build();
RoomArea room4 = RoomArea.builder().roomName("Sala").area(100).build();
RoomArea room5 = RoomArea.builder().roomName("Comedor").area(16).build();
RoomArea room6 = RoomArea.builder().roomName("Cocina").area(12).build();
List<RoomArea> rooms = new ArrayList<>();
rooms.add(room1);
rooms.add(room2);
rooms.add(room3);
rooms.add(room4);
rooms.add(room5);
rooms.add(room6);
return Response.builder()
.nameHouse("Casa Familiar")
.totalArea(206.0)
.totalPrice(515000.0)
.biggestRoom(RoomDTO.builder()
.roomName("Sala")
.roomWidth(10)
.roomLength(10)
.build())
.roomAreas(rooms)
.build();
}
当我在 objectWriter 之后打印它时,它看起来像这样:
{
"nameHouse" : "Casa Familiar",
"totalArea" : 206.0,
"totalPrice" : 515000.0,
"biggestRoom" : {
"roomName" : "Sala",
"roomWidth" : 10.0,
"roomLength" : 10.0
},
"roomAreas" : [ {
"roomName" : "Recamara Principal",
"area" : 25.0
}, {
"roomName" : "Recamara Daniel",
"area" : 28.0
}, {
"roomName" : "Recamara Julieta",
"area" : 25.0
}, {
"roomName" : "Sala",
"area" : 100.0
}, {
"roomName" : "Comedor",
"area" : 16.0
}, {
"roomName" : "Cocina",
"area" : 12.0
} ]
}
有人知道我为什么会遇到这个问题吗?
【问题讨论】: