dimanche 4 août 2019

Writing tests for Polyglot Springboot with both JPATest and MongoDB Test

I am setting up a new Springboot 2 application which uses both an MYSQL database and a MongoDB database for Data storage.

I am unable to understand how I can write a class for tests which use both DataJPA and DataMongo.

Setting up queries across the two for real uses was a relatively simple task by using Services which use both JPA Repositories and Mongo Repositories.

When it comes to write test cases, I am able to write tests for just the JPA entities (@DataJPATest) or for just the Mongo entities (@DataMongoTest) with ease using H2 and Embedded Mongo.

It's not possible to define a test class with both JPA and Mongo annotations because Spring allows only 1 bootstrap.

This is the class from JPA MYSQL:

@Entity
@Data
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Size(max = 255)
    private String name;

    @Size(max = 1000)
    private String description;
}


Classes for Mongo Repos:

@Document
@Data
public class Review {

    @Id
    private String id;

    @Indexed
    private String title;

    private String reviewText;

    private boolean recommended;

    @Indexed
    private Integer productId;

    @DBRef
    private List<Comment> comments;
}

@Document
@Data
public class Comment {

    @Id
    private String id;

    private String title;

    private String commentText;
}

Sample expected tests class:

@RunWith(SpringRunner.class)
@DataJpaTest
@DataMongoTest
public class ReviewRepositoryTests {

    @Autowired
    TestEntityManager entityManager;

Writing a test class with both DataJPA and DataMongo results in this stack error:

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [xyz.cybersapien.tech.reviews.ReviewRepositoryTests]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTestContextBootstrapper)]

    at org.springframework.test.context.BootstrapUtils.resolveExplicitTestContextBootstrapper(BootstrapUtils.java:166)
    at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:127)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:124)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:142)

Aucun commentaire:

Enregistrer un commentaire