我正在使用内存数据库(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
}
}
服务实现应使用存储在内存数据库中的数据,并且很少执行业务验证。我在这里面临的问题是服务实现实际上是在考虑ManufacturerRepository实例,该实例指向实际的db(在这种情况下为postgres),而不是指向内存数据库。如何将ManufacturerRepository实例注入到指向内存数据库的ManufacturerServiceImpl服务实现中的任何帮助
答案 0 :(得分:3)
在运行集成测试时使用Spring-Profiles来使用H2,否则在另一个DB上使用
。将application-test.{yml|properties}
添加到资源中,并将@ActiveProfiles("test")
添加到您的班级。
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
答案 1 :(得分:1)
如果您想使用首选数据库 (testContainer - Docker) 进行集成测试,请检查答案 here