Reputation: 399
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
Upvotes: 3
Views: 14529
Reputation: 5594
If you want integration test with your preferred DB (testContainer - Docker is what you are looking - Extremely easy), check answer here
Upvotes: 2
Reputation: 6140
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
Upvotes: 11