Search code examples
javaspringspring-bootrestjunit

Spring Boot integration test. How to test the 'DELETE' method?


I'm using Spring Boot 2.5.6 and JUnit 4.13.2. My task is to test the DELETE method

My REST controller:

@RestController
public class DomainEndpoint {

    private final SomeService service;

    @DeleteMapping("/domain/{id}")
    public void delete(@PathVariable long id) {
        service.delete(id);
    }
}

My test:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class DomainEndpointTest {

    @Autowired
    TestRestTemplate template;

    @MockBean
    SomeService service;

    @Test
    public void delete() {
        String url = "/domain/123";
        ResponseEntity<?> resp = template.exchange(url, HttpMethod.DELETE, new HttpEntity<>(""), String.class);
        assertEquals(HttpStatus.NO_CONTENT, resp.getStatusCode());
    }
}

As you can see, the only solution for testing the 'DELETE' method, which I found, is:

ResponseEntity<?> resp = template.exchange(url, HttpMethod.DELETE, new HttpEntity<>(""), String.class);

But params for body new HttpEntity<>("") and for return type String.class seem strange to me. Why should I use them? Can I do the same more straightway without passing unnecessary parameters?
On the other hand, TestRestTemplate template has a set of short and readable methods delete(). The problem with them - they return void and I can't check the response status code in this case.

The main question is how to test DELETE methods correctly?


Solution

  • Instead of passing in new HttpEntity<>("") HttpEntity has a special class variable you can use called HttpEntity.EMPTY for these situations. You can also use a return type of void.

    ResponseEntity<Void> resp = template.exchange(url, HttpMethod.DELETE, HttpEntity.EMPTY, Void.class);