【问题标题】:How to configure Spring boot testing database?How to configure Spring boot testing database?
【发布时间】:2022-12-27 19:14:06
【问题描述】:

I am trying to use H2Database for my Spring boot Project. I added all configration but it collecting to the real database instead of h2 mem database. Please help someone to configure it.

【问题讨论】:

    标签: spring-boot-test


    【解决方案1】:

    To configure a testing database in Spring Boot, you can follow these steps:

    First, you will need to include the appropriate dependency in your project. For example, if you are using H2 as your testing database, you can include the following dependency in your pom.xml file:

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
    </dependency>
    

    Next, you will need to configure your testing database in the application.properties file. You can do this by adding the following properties:

    spring.datasource.url=jdbc:h2:mem:testdb
    spring.datasource.username=sa
    spring.datasource.password=
    spring.datasource.driverClassName=org.h2.Driver
    

    You can then use the @DataJpaTest annotation to enable the testing support for JPA repositories. This will configure an in-memory database, scan for @Entity classes, and configure Spring Data JPA repositories.

    If you want to customize the configuration of the testing database, you can create a configuration class that is annotated with @TestConfiguration and define the beans for the data source and JPA repositories in this class.

    Finally, you can use the TestEntityManager to perform database operations in your test methods, such as saving and finding entities.

    I hope this helps! Let me know if you have any questions or need further assistance.

    【讨论】:

      猜你喜欢
      • 2022-12-19
      • 2022-12-27
      • 2022-12-19
      • 2022-12-01
      • 2022-12-26
      • 2022-12-02
      • 2022-12-02
      • 2022-12-02
      • 2022-12-01
      相关资源
      最近更新 更多