简体   繁体   中英

Integration test in Spring Boot using in-memory database

I am doing integration testing using in-memory database(H2) so that I can populate the repository with known values, initialize the service implementation with the repo. Here is my test class

@RunWith(SpringRunner.class)
@TestPropertySource("classpath:application-test.properties")
@SpringBootTest
public class ManufacturerServiceH2ImplTest {

    @Autowired
    private ManufacturerRepository manufacturerRepository;

    @Autowired
    ManufacturerServiceImpl manufacturerServiceImpl;


    @Test
    public void testManufacturerCreate() throws Exception {

        //Create Manufacturer
        Manufacturer manufacturer = new Manufacturer();
        manufacturer.setManufacturerId("SSS");
        manufacturer.setManufacturerName("WWW");

        //Save Manufacturer in Inmemory 
        Manufacturer manufacturerInMemory = manufacturerRepository.save(manufacturer);

        //Service Implementation
        StResponse createManufacturer = manufacturerServiceImpl.createManufacturer(manufacturer);

        //Compare the result

    }

}

The service implementation should use the data saved in the in-memory database and perform few business validation. The issue which I am facing here is that the service implementation is actually considering the manufacturerRepository instance which is pointing to the actual db(postgres in this case) rather than pointing to the in memory database. Any help of how to inject the manufacturerRepository instance into manufacturerServiceImpl service implementation that points out to inmemory database

Use Spring-Profiles to use H2 when integrationtests are running and otherwise another DB.

Add application-test.{yml|properties} to the ressources and @ActiveProfiles("test") to your class.

application-test.yml

spring.profiles.active: test

spring:
  jpa:
    database: h2
  datasource:
    url: jdbc:h2:mem:AZ
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true

如果您想使用首选数据库(testContainer - Docker)进行集成测试,请在此处查看答案

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM