3

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

1
  • 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 Commented Jul 18, 2019 at 15:40

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

If you need a working example have a look at my project: gitlab.com/phip1611/phips-photoblog/blob/dev/…
Works. However I also needed to set ddl-auto: create-drop in order to work.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.