Configure specific in memory database for testing purpose in Spring

前端 未结 7 799
粉色の甜心
粉色の甜心 2020-12-07 13:19

How do I configure my Spring Boot application so that when I run unit tests it will use in-memory database such as H2/HSQL but when I run Spring Boot application it will use

7条回答
  •  Happy的楠姐
    2020-12-07 14:08

    Another approach is to add the annotation @AutoConfigureTestDatabase to you test class. My tests usually look like this:

    @RunWith(SpringRunner.class)
    @DataJpaTest
    @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
    public class MyRepositoryTest {
    
        @Autowired
        MyRepository repository;
    
        @Test
        public void test() throws Exception {
            // Tests...
        }
    }
    

    Note that the embedded database dependency needs to be added in the pom.xml file. For embedded database this annotation is not necessary it will work even if only the dependency is added in pom file.

提交回复
热议问题