我正在控制器中测试一个只返回字符串并使用 Mockito 模拟服务调用的 post 方法。我的问题是,当在控制器上调用服务方法时,它会返回 null。
@RunWith(SpringRunner.class)
@WebMvcTest(ProcessGroupController.class)
public class ProcessGroupRestControllerTest {
.............
@Test
public void givenAllNifiArguments_whenImportProcessGroup_thenReturnJsonOk() throws Exception {
NiFiArguments niFiArguments = NiFiArguments.builder()......flowVersion("3").build();
String expected = "1689d61b-624d-4574-823d-f1b4755882e1";
String json = mapper.writeValueAsString(niFiArguments);
//Mock service call
when(nifiService.importProcessGroup(niFiArguments)).thenReturn(expected);
mvc.perform(post("/nifi/pg-import").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isCreated())......);
}
控制器:
@PostMapping("/pg-import")
public ResponseEntity<String> importProcessGroup(@RequestBody NiFiArguments niFiArguments)
throws NiFiClientException {
log.info("Called method importFlow");
String result = nifiService.importProcessGroup(niFiArguments);
return new ResponseEntity<String>(result, HttpStatus.CREATED);
}
字符串结果 = 空
我有类似的测试返回 POJO,它工作得很好
正如 ekalin 所说,我的构建器类需要实现 equals 和 hashcode:
@Builder
@Getter
@EqualsAndHashCode
public class NiFiArguments {
private String bucketIdentifier;
private String flowIdentifier;
private String flowVersion;
private String baseUrl;
}