我正在我的控制器中测试一个 post 方法,它只返回一个 String 并使用 Mockito 来模拟服务调用。我的问题是,当在控制器上调用服务方法时,它返回 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);
}
字符串结果 = null
我有类似的测试返回一个 POJO,它工作得很好