我正在嘗試學習 Junit,但最終遇到了我的測驗用例回傳 200 狀態代碼但回傳空回應正文的情況。它只是一個使用 JPA 存盤庫的簡單保存操作,我嘗試了許多在線解決方案,但沒有一個對我有用。
測驗類:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
class CarManufacturingSystemApplicationTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private GroupController groupController;
ObjectMapper om = new ObjectMapper();
@Test
public void createGroupTest() throws Exception {
GroupCreateRequest createRequest = new GroupCreateRequest();
createRequest.setActiveFlag(true);
createRequest.setGroupName("test");
createRequest.setPlantCode(1L);
String expectedjson = "{\r\n" "\"message\": \"Group created successfully\"\r\n" "}";
MvcResult result = mockMvc.perform(post("/group/createGroup")
.contentType(MediaType.APPLICATION_JSON_VALUE).accept(MediaType.APPLICATION_JSON_VALUE).content(new Gson().toJson(createRequest)))
.andExpect(status().isOk())
.andReturn();
String actualJson = result.getResponse().getContentAsString();
Assert.assertEquals(expectedjson, actualJson);
}
控制器:
@RestController
@RequestMapping(value = "/group")
public class GroupController {
@Autowired
private GroupService groupService;
@PostMapping("/createGroup")
public ResponseEntity<Response> createGroup(@RequestBody GroupCreateRequest groupCreateRequest) {
Response response = groupService.createGroup(groupCreateRequest);
return new ResponseEntity<> (response, HttpStatus.OK);
}
}
錯誤:
org.junit.ComparisonFailure: expected:<[{
"message": "Group created successfully"
}]> but was:<[]>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.nissan.car.manufacturing.system.CarManufacturingSystemApplicationTests.createGroupTest(CarManufacturingSystemApplicationTests.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
服務實施
public Response createGroup(GroupCreateRequest groupCreateRequest) {
Group group = new Group();
Response response = new Response();
try {
addGroupDetails(groupCreateRequest, group);
groupRepository.save(group);
uj5u.com熱心網友回復:
請注意,您正在測驗GroupController,而不是GroupService,因此您應該模擬GroupService. 請更換
@MockBean
private GroupController groupController;
到
@MockBean
private GroupService groupService;
然后使用簡單的存根指令when(something).thenReturn(somethingElse)使您groupService回傳您指定的回應。
@Test
public void createGroupTest() throws Exception {
// ...
Response response = new Response();
response.setMessage("Group created successfully");
when(groupService.createGroup(any())).thenReturn(response);
// ...
Assert.assertEquals(expectedjson, actualJson);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/467596.html
