简体   繁体   中英

Spring MVC Controller testing PUT

Trying to test my web tier (spring boot, spring mvc) with junit5 and mockito. All other tests on http methods (get, put, ...) are working fine but the update. Following the code.

Controller:

@PutMapping(value = "{id}")
public ResponseEntity<?> putOne(@PathVariable Integer id, @Valid @RequestBody Customer customerToUpdate) {
    Customer updated = customerService.update(id, customerToUpdate);
    return ResponseEntity.ok(updated);
}    

Service:

public Customer update(Integer customerId, Customer customerToUpdate) {
    Customer customerFound = customerRepository.findById(customerId).orElseThrow(() -> {
        throw new CustomerControllerAdvice.MyNotFoundException(customerId.toString());
    });

    customerToUpdate.setId(customerFound.getId());

    return customerRepository.save(customerToUpdate);
}

Finally the test:

static final Customer oneCustomer = Customer.of(3,"john", LocalDate.of(1982, 11, 8));
    
@Test
void putOneTest() throws  Exception {
    when(customerService.update(oneCustomer.getId(), oneCustomer)).thenReturn(oneCustomer);

    mockMvc.perform(put(CUSTOMER_URL + oneCustomer.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(objectMapper.writeValueAsString(oneCustomer)))
            .andDo(print())
            .andExpect(jsonPath("$.name").value(oneCustomer.getName()))
                .andExpect(jsonPath("$.birthDate").value(oneCustomer.getBirthDate().toString()))
                .andExpect(status().isOk());
}

Result:

java.lang.AssertionError: No value at JSON path "$.name"

update(...) method in CustomerService return just null. Can't understand way. Please advice.

The problem is this line:

when(customerService.update(oneCustomer.getId(), oneCustomer)).thenReturn(oneCustomer);

You should change it to

when(customerService.update(eq(oneCustomer.getId()), any())).thenReturn(oneCustomer);

Because your put request body is a JSON , not a real Customer , the when...thenReturn statement didn't work well as you expected. The mocked customerService returns a null by default. This is why you got a empty response. So you must to correct the argument matcher to make it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM