使用内存数据库在Spring Boot中进行集成测试

sha*_*ank 0 java junit spring jpa spring-boot

我正在使用内存数据库(H2)进行集成测试,以便可以使用已知值填充存储库,并使用存储库初始化服务实现。这是我的考试课

@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

    }

}
Run Code Online (Sandbox Code Playgroud)

服务实现应使用保存在内存数据库中的数据,并且很少执行业务验证。我在这里面临的问题是服务实现实际上是在考虑ManufacturerRepository实例,该实例指向实际的db(在这种情况下为postgres),而不是指向内存数据库。关于如何将指示厂商数据库指向内存数据库的ManufacturerRepository实例注入厂商serviceImpl服务实现的任何帮助

phi*_*611 5

当运行集成测试时,使用Spring-Profiles来使用H2,否则运行另一个DB。

添加application-test.{yml|properties}到资源和@ActiveProfiles("test")您的班级。

应用程序测试

spring.profiles.active: test

spring:
  jpa:
    database: h2
  datasource:
    url: jdbc:h2:mem:AZ
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true
Run Code Online (Sandbox Code Playgroud)