I'm doing a battery tests in a Spring Boot applications, using in memory MongoDbTest, and my test for testing unique/non-duplicate indexes is failing (it lets me create records with duplicate keys, and the relevant test fail).
For declaring the unique index, I'm using the annotations @Indexed(unique=true)
This is my code
Entity class
@Document(collection="products")
public class ProductEntity {
// Id internal (db managed id)
@Id
private String id;
// Used for manage optimistic locking
@Version
private Integer version;
// Create unique index (external id)
@Indexed(unique = true)
private int productId;
private String name;
private int weight;
public ProductEntity(int productId, String name, int weight) {
this.productId = productId;
this.name = name;
this.weight = weight;
}
}
Test class
@DataMongoTest
public class PersistenceTests {
@Autowired
private ProductRepository repository;
private ProductEntity savedEntity;
@BeforeEach
public void setupDb() {
repository.deleteAll();
ProductEntity entity = new ProductEntity(1, "n", 1);
savedEntity = repository.save(entity);
assertEqualsProduct(entity, savedEntity);
}
@Test
public void duplicateError() {
ProductEntity entity = new ProductEntity(savedEntity.getProductId(), "n", 1);
Assertions.assertThrows(DuplicateKeyException.class, () -> {
repository.save(entity);
});
}
}
Repository
public interface ProductRepository extends PagingAndSortingRepository<ProductEntity, String> {
Optional<ProductEntity> findByProductId(int productId);
}
The embed MongoDB is declared as dependency in my build.gradle as
// Embedded MongoDB for test only
testImplementation('de.flapdoodle.embed:de.flapdoodle.embed.mongo')