0

I'm testing a post method in my controller that only return a String and using Mockito to mock the service call. My problem is that when the service method is called on controller it return 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())......);
    }

The controller:

    @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);
    }

String result = null

I have similar tests that return a POJO and it works perfectly

Aldo Inácio da Silva
  • 824
  • 2
  • 14
  • 38
  • 1
    Does NiFiArguments have an equals() method? If not, then the instance that you use to setup the mock and to call the method won't be considered equal (they're not the same), and the mock call will not be matched. – ekalin May 15 '20 at 13:37

1 Answers1

0

As ekalin said my builder class needed to implement equals and hashcode:

@Builder
@Getter
@EqualsAndHashCode
public class NiFiArguments {

    private String bucketIdentifier;
    private String flowIdentifier;
    private String flowVersion;
    private String baseUrl;
}

Aldo Inácio da Silva
  • 824
  • 2
  • 14
  • 38