### Question:
ConsumerService { public Optional<Consumer> upsert(Consumer consumer) throws ValidationException { return !read(consumer.getKey()).isPresent() ? create(consumer) : update(consumer); }  Optional<Consumer> create(Consumer consumer); Optional<Consumer> update(Consumer consumer); Optional<Consumer> upsert(Consumer consumer); Optional<Consumer> read(ConsumerKey key); List<Consumer> findAll(Predicate<Consumer> filter); void delete(Consumer consumer); boolean exists(ConsumerKey key);  }### Answer:
@Test public void upsert() { final ConsumerKey key = mock(ConsumerKey.class); final Specification specification = mock(Specification.class); final Consumer entity = mock(Consumer.class); final Consumer existingEntity = mock(Consumer.class); when(entity.getKey()).thenReturn(key); when(consumerRepository.findById(key)).thenReturn(Optional.of(existingEntity)); doNothing().when(consumerValidator).validateForUpdate(entity, existingEntity); when(handlerService.handleUpdate(entity, existingEntity)).thenReturn(specification); when(consumerRepository.save(entity)).thenReturn(entity); consumerService.upsert(entity); verify(entity, times(2)).getKey(); verify(consumerRepository, times(2)).findById(key); verify(consumerValidator).validateForUpdate(entity, existingEntity); verify(handlerService).handleUpdate(entity, existingEntity); verify(consumerRepository).save(entity); }