I have a simple repository implementation like this.
@Repository
public interface PolicyRepository extends ReactiveMongoRepository<Policy, String> {
@Query("{ id: { $exists: true }}")
Flux<Policy> findAllPaged(Pageable pageable);
@Query("{ name: { $eq: ?0 }}")
Mono<Policy> findByName(String name);
}
And A simple Action Method on a controller like this.
@ResponseStatus(HttpStatus.CREATED)
public Mono<ResponseEntity<String>> createPolicy(@Valid @RequestBody Policy policy) {
//Use The Mongodb ID Generator
policy.setId(ObjectId.get().toString());
return policyRepository.findByName(policy.getName()).flatMap(policy1 -> {
return Mono.just(ResponseEntity.badRequest().body("A Policy with the same name as the policy you are trying to create" +
"already exists"));
}).switchIfEmpty(
policyRepository.save(policy).map(p2 ->{
eventPublisher.publish(Events.POLICY_CREATED, p2.getId());
return ResponseEntity.status(HttpStatus.CREATED).body("Policy definition created successfully");
}));
}
What I was looking to achieve was return a bad request if there exists a policy with the same name as the one being inserted or do the save operation if the findByName method returns empty.
The strange behavior is that The following test fails because save is always called whether or not findByName returns data or not.
Here is the test
@Test
void testCreateDuplicatePolicyShouldFail() {
given(policyRepository.findByName(eq(policy.getName()))).willReturn(Mono.just(policy));
given(policyRepository.save(any(Policy.class))).willReturn(Mono.just(policy));
given(eventPublisher.publish(Events.POLICY_CREATED, policy.getId())).willReturn(Mono.just(0L));
webTestClient.post().uri("/policies")
.syncBody(policy)
.exchange()
.expectStatus().isBadRequest();
verify(policyRepository, times(1)).findByName(eq(policy.getName()));
verify(policyRepository, times(0)).save(any(Policy.class));
verify(eventPublisher, times(0)).publish(Events.POLICY_CREATED, policy.getId());
}
And it fails with the following exception
org.mockito.exceptions.verification.NeverWantedButInvoked:
com.management.dashboard.repository.PolicyRepository#0 bean.save(
<any com.management.core.model.Policy>
);
Please am I doing something wrong. Any pointer will be deeply appreciated.