To set up an in-memory database for testing in Spring, you can follow these steps:
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>
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
Add the @DataJpaTest annotation to your test class to enable Spring Data JPA testing.
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);
}
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
Asked: 2023-05-30 14:08:56 +0000
Seen: 10 times
Last updated: May 30 '23
How do you log Python data into a database?
How can the SQL debug mode be activated in PostgreSQL version 15.2?
How to deal with an operational error when connecting Django to MySQL?
What is the method for choosing data FROM a stored procedure?
How can SQL/PLSQL blocks be stripped of their comments?
What is the process for initializing Java UDFs in Spark?
How to set up Database First configuration in Entity Framework 7 for MVC 6?