2

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

João Pedro Schmitt
  • 1,046
  • 1
  • 11
  • 25
shashank
  • 379
  • 5
  • 6
  • 15
  • I'm not an expert in testing but I think the proper terminology in this case is integration testing rather than unit testing because the whole spring boot context get's started – phip1611 Jul 18 '19 at 15:40

2 Answers2

11

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
phip1611
  • 5,460
  • 4
  • 30
  • 57
  • If you need a working example have a look at my project: https://gitlab.com/phip1611/phips-photoblog/blob/dev/phips-photoblog-service/src/main/resources/application-h2.yml – phip1611 Jul 18 '19 at 15:39
  • 1
    Works. However I also needed to set `ddl-auto: create-drop` in order to work. – Tobias May 10 '20 at 08:52
2

If you want integration test with your preferred DB (testContainer - Docker is what you are looking - Extremely easy), check answer here

Ravi Parekh
  • 5,253
  • 9
  • 46
  • 58