Mock a service to return an empty list to test 404 status code

Viewed 551

I've attempting to test this REST service such that a NOT_FOUND (404) error is thrown when itemService.getActiveItems() returns an empty List:

@GetMapping("/items/active")
public ResponseEntity<List<ItemEntity>> getActiveItems() {

    List<ItemEntity> activeItems = itemService.getActiveItems();
    if (activeItems.isEmpty()) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else {
        return new ResponseEntity<>(activeItems, HttpStatus.OK);
    }
}

I use the TestRestTemplate to test :

     @Mock
     private ItemService itemService;
    
            @Test
            public void activeItemsTest() {
            private TestRestTemplate templateAuth;
        
        when(itemService.getActiveItems()).thenReturn(new ArrayList());
            
                    ResponseEntity<List<ItemEntity>> result = templateAuth.exchange("/items/active", HttpMethod.GET,
                            null, new ParameterizedTypeReference<List<ItemEntity>>() {
                            });
                    Assertions.assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
        }

I'm trying to cause the "/items/active" endpoint to return new ResponseEntity<>(HttpStatus.NOT_FOUND); as I have mocked itemService.getActiveItems() to return an empty ArrayList. When I test result.getStatusCode() does not contain 404. How should I amend my test in order to return a 404 error code ?

1 Answers

You could use JUnit 5 and annotate the class with @ExtendWith(MockitoExtension.class) and @SpringBootTest. Then change

 @Mock
 private ItemService itemService;

to

 @SpyBean
 private ItemService itemService;

so that you can mock the behaviour of the service that is autowired into the Controller

Related