Ask Your Question

Revision history [back]

To set up an in-memory database for testing in Spring, you can follow these steps:

  1. Add the required dependencies to your project. For example, if you are using H2 database, add the following dependency to your pom.xml file:

    <dependency>
       <groupId>com.h2database</groupId>
       <artifactId>h2</artifactId>
       <version>1.4.200</version>
       <scope>test</scope>
    </dependency>
    
  2. Configure the in-memory database in your test configuration. For example, if you are using H2 database, you can add the following configuration in your test application.properties file:

    spring.datasource.url=jdbc:h2:mem:test
    spring.datasource.driverClassName=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=
    spring.h2.console.enabled=true
    spring.h2.console.path=/h2-console
    
  3. Add the @DataJpaTest annotation to your test class to enable Spring Data JPA testing.

  4. Use the JdbcTemplate or EntityManager to perform database operations in your tests.

    For example, you can use the following code to insert data into the database:

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Test
    public void testInsertData() {
       String sql = "INSERT INTO employee (id, name, salary) VALUES (1, 'John', 5000)";
       jdbcTemplate.execute(sql);
    }
    

    Alternatively, you can use the EntityManager to insert data into the database:

    @Autowired
    private EntityManager entityManager;
    
    @Test
    public void testInsertData() {
       Employee employee = new Employee();
       employee.setId(1L);
       employee.setName("John");
       employee.setSalary(5000);
    
       entityManager.persist(employee);
    }