vendredi 16 avril 2021

Test for the PUT method responsible for creating a new entity by TestRestTemplate in the E2E test

I'm building my app with Spring. I am currently trying to test a PUT method that can both update and create an entity called Tank:

public class Tank {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;
    private boolean tested;
    @NotBlank(message = "Name must be not empty")
    private String name;
    private LocalDateTime productionDate;
   
    public Tank() {}

    public Tank(@NotBlank(message = "Name must be not empty") String name, LocalDateTime productionDate) {
        this.name = name;
        this.productionDate = productionDate;
    }

My PUT method in the controller looks like this:

@Transactional
    @PutMapping("tanks/{id}")
    public ResponseEntity<?> updateTask(@PathVariable int id, @RequestBody Tank source) {
        if(repository.existsById(id)) {
            logger.warn("Updating given tank");
            repository.findById(id)
                    .ifPresent(tank -> tank.update(source));
            return ResponseEntity.noContent().build();
        }
        else {
            logger.warn("Creating new tank with given id");
            var newTank = repository.save(source);
            return ResponseEntity.created(URI.create("/" + newTank.getId())).body(newTank);
        }
    }

everything works. I can both update an existing tank and create a new one. The problem comes when I want to test it.

 @Test
    void httpPut_createsNewTank_returnsResponseEntity() throws JSONException {
        // given
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        // and
        String entity = new JSONObject()
                .put("name", "PUT")
                .put("productionDate", "2020-12-02T12:23:00")
                .toString();
        // and
        HttpEntity<String> request = new HttpEntity<>(entity, headers);
        // and
        int id = repo.findAll().size() + 1;
        URI expectedLocation = URI.create("/" + id);

        // when
        var result = testRestTemplate.exchange(baseUrl + port + "/" + id, HttpMethod.PUT, request, Tank.class);

        // then
        assertThat(result.getBody().getName()).isEqualTo("PUT"); // expected: "PUT"   actual: null
        assertThat(result.getHeaders().getLocation()).isEqualTo(expectedLocation); // expected: /1   actual: null
    }

This is a test placed in the E2E test run on RANDOM_PORT where I am using TestRestTemplate. Testing of other methods works fine, so it is not the fault of some configuration. My question is why does the exchange method return body and headers as null?

Aucun commentaire:

Enregistrer un commentaire