How to verify that my sendMessage method is called with Msg.SAVE or with Msg.UPDATE using mockito's verify method.
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
private final SendMessageInTopic messageInTopic;
public CustomerService (CustomerRepository customerRepository, SendMessageInTopic messageInTopic)
{
this.customerRepository = customerRepository;
this.messageInTopic= messageInTopic;
}
public Customer saveCustomer(Customer savedCustomer) {
Customer customer = customerRepository
.findCustomerByEmail(savedCustomer.getEmail());
if(customer != null) {
customer.setFirstName(savedCustomer.getFirstName());
customer.setLastName(savedCustomer.getLastName());
customer.setPhoneNumber(savedCustomer.getPhoneNumber());
messageInTopic.sendMessage(savedCustomer.getId(),Msg.SAVE)
} else {
customer = new Customer();
customer.setFirstName(savedCustomer.getFirstName());
customer.setLastName(savedCustomer.getLastName());
customer.setEmail(savedCustomer.getEmail());
customer.setPhoneNumber(savedCustomer.getPhoneNumber());
messageInTopic.sendMessage(savedCustomer.getId(),Msg.Update)
}
return customerRepository.save(customer);
}
}
public class CustomerServiceTest{
private final CustomerRepository customerRepository = mock(CustomerRepository.class);
private final CustomerService customerService = mock(CustomerService.class);
private final SendMessageInTopic messageInTopic = mock(SendMessageInTopic.class);
private final CustomerMapper customerMapper = mock(CustomerMapper.class);
@Test
void whenSaveCustomerThenMsgSAVEOrUPDATE() {
// Given
final var customerId = "123456";
final var customer =
new CustomerDto(ensUserId, 'james', 'GREWAN', '32766666', 'j.grewan@gree.com');
final customerEntity = mock(Customer.class);
when(customerRepository.findCustomerByEmail(customer.getEmail())
.thenReturn(Optional.of(customerEntity));
when(customerRepository.save(customerEntity)).thenReturn(customerEntity);
when(customerMapper.toDto(customerEntity)).thenReturn(customer);
// When
final var result = customrService.saveCustomer(customer);
// Then
assertEquals(result, customer);
verify(messageInTopic, times(1)).sendMessage(result.getId(),Msg.SAVE);
}
}
verify(messageInTopic, times(1)).sendMessage(result.getId(),Msg.SAVE); : This is where I will test if I call my sendMessage method with the Msg.SAVE parameter in the create case or the Msg.UPDATE parameter in the update case.
how to do this test please ?