Skip to content

Instantly share code, notes, and snippets.

@SDiamante13
Last active March 13, 2020 01:03
Show Gist options
  • Select an option

  • Save SDiamante13/ba890a8eb10829056d91942ff6befb20 to your computer and use it in GitHub Desktop.

Select an option

Save SDiamante13/ba890a8eb10829056d91942ff6befb20 to your computer and use it in GitHub Desktop.
An example of using Mockito's Answer when saving an customer.
@Test
public void saveCustomer_savesTheCustomerToTheDatabaseWithAnAutoGeneratedId() {
// Arrange
when(customerRepository.save(any()))
.thenAnswer(savedCustomerWithAutoGeneratedId());
Customer customer = Customer.builder()
.firstName("Sam")
.lastName("Adams")
.build();
// Act
Customer result = customerService.saveCustomer(customer);
// Assert
Assertions.assertThat(result).isEqualTo(customer);
}
private Answer<Customer> savedCustomerWithAutoGeneratedId() {
return invocation -> {
Customer savedCustomer = invocation.getArgument(0);
savedCustomer.setCustomerId(1L);
return savedCustomer;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment