From b0459ae0984b5e9b3486a758d099f1eec7a44053 Mon Sep 17 00:00:00 2001 From: "vincenzo.corso" Date: Wed, 27 Mar 2024 07:53:18 +0100 Subject: [PATCH] test(rent-service): add test for optimistic locking --- ...entJPARepositoryAdapterIntegrationTest.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/rent-service/src/int-test/java/it/vincenzocorso/carsharing/rentservice/adapters/persistence/jpa/RentJPARepositoryAdapterIntegrationTest.java b/rent-service/src/int-test/java/it/vincenzocorso/carsharing/rentservice/adapters/persistence/jpa/RentJPARepositoryAdapterIntegrationTest.java index 5d362dc..a314e11 100644 --- a/rent-service/src/int-test/java/it/vincenzocorso/carsharing/rentservice/adapters/persistence/jpa/RentJPARepositoryAdapterIntegrationTest.java +++ b/rent-service/src/int-test/java/it/vincenzocorso/carsharing/rentservice/adapters/persistence/jpa/RentJPARepositoryAdapterIntegrationTest.java @@ -1,5 +1,6 @@ package it.vincenzocorso.carsharing.rentservice.adapters.persistence.jpa; +import it.vincenzocorso.carsharing.common.messaging.events.ResultWithEvents; import it.vincenzocorso.carsharing.rentservice.adapters.persistence.RentWrapper; import it.vincenzocorso.carsharing.rentservice.domain.models.RandomRent; import it.vincenzocorso.carsharing.rentservice.domain.models.Rent; @@ -23,7 +24,9 @@ import java.util.stream.Stream; import static it.vincenzocorso.carsharing.rentservice.domain.models.RandomRent.randomRent; +import static it.vincenzocorso.carsharing.rentservice.domain.models.RentState.PENDING; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatException; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest @@ -139,9 +142,22 @@ void shouldFindRentsByPagination() { assertThat(retrievedRentsIds).hasSize(savedRents.size() - 1); } + @Test + void shouldThrowExceptionWhenOptimisticLockFails() { + Rent rent = this.rentJPARepositoryAdapter.save(randomRent(PENDING)); + Rent loadedRent1 = this.rentJPARepositoryAdapter.findById(rent.getId()).orElseThrow(); + Rent loadedRent2 = this.rentJPARepositoryAdapter.findById(rent.getId()).orElseThrow(); + loadedRent1.accept(); + loadedRent2.reject(); + + Rent savedRent = this.rentJPARepositoryAdapter.save(loadedRent1); + assertThatException().isThrownBy(() -> this.rentJPARepositoryAdapter.save(loadedRent2)); + assertThat(((RentWrapper)savedRent).getVersion()).isEqualTo(((RentWrapper)loadedRent1).getVersion() + 1); + } + private List initializeRentsTable() { RentEntityMapper rentMapper = new RentEntityMapper(); - return Stream.of(RentState.PENDING, RentState.STARTED, RentState.ENDED) + return Stream.of(PENDING, RentState.STARTED, RentState.ENDED) .map(RandomRent::randomRent) .peek(rent -> rent.setId(null)) .map(rentMapper::convertToEntity)