Ask Your Question
1

How can a particular in-memory database be set up for the purpose of testing in Spring?

asked 2023-05-30 14:08:56 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-30 14:30:01 +0000

huitzilopochtli gravatar image

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);
    }
    
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-30 14:08:56 +0000

Seen: 10 times

Last updated: May 30 '23