spring-bootspring-mvccontrollermockitospring-mvc-test

Specify mock to get null and call to the else block


I am new to Java and have been looking up for answers but I must be missing it. So here is the question:

This is my controller:

public REntity<IModel> getPersonById(
        @PathVariable("id") @Parameter(description = "The id to retrieve") String id) {

        IModel response = this.myService.getPersonById(id);
        if (response != null) {
            return REntity.ok().body(response);
        } 
        else {
            return REntity.notFound().build();
        }
    }

Contents of the test method:

mockMvc.perform(get("/issuers/{id}", "123")).andExpect(status().is(404));

How can I call the else block? I can't pass a null to the id param. The service also doesn't return null. Is there a mock to return null when the service is called?


Solution

  • You will need to create a mock of your service that returns null for a given id:

    final MyService myService = mock(MyService.class);
    when(myService.getPersonById("123").thenReturn(null);