Repository Unit Testing Flashcards

https://medium.com/javarevisited/getting-started-with-unit-testing-in-spring-boot-bada732a5baa

1
Q

Configuring Database

A

Use an in-memory database like H2 for testing. Spring Boot will auto-configure it for you. In-memory databases like H2 are lightweight and optimized for fast operations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

@DataJpaTest

A

Annotate your test class with @DataJpaTest. This annotation configures the minimal configuration required to test JPA applications.
@DataJpaTest will automatically configure an in-memory database, scan for @Entity classes, and configure Spring Data JPA repositories.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Example

A

package com.dharshi.unitTesting.repositoryTests;

@DataJpaTest
public class UserRepositoryTests {

@Autowired
private UserRepository userRepository;

@Test
@Transactional
@Rollback
public void testSaveUser() {
    // Define test data
    String name = "test1";
    String email = "test1@example.com";

    // Create a User object with the test data
    User user = User.builder()
            .name(name)
            .email(email)
            .build();

    // Save the user to the database
    User savedUser = userRepository.save(user);

    // Assert that the retrieved user is not null
    assertNotNull(savedUser);

    // Assert that the retrieved user id is not null
    assertNotNull(savedUser.getId());

    // Assert that the retrieved user's name matches the expected name
    assertEquals(name, savedUser.getName());

    // Assert that the retrieved user's email matches the expected email
    assertEquals(email, savedUser.getEmail());
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explanation

A

@DataJpaTest is used to set up a JPA test environment with an in-memory database

@Autowired injects the UserRepository into the test class.

@Transactionalensures that the test method runs within a transactional context. Changes made during the test are not persisted beyond the scope of the test method unless explicitly committed.

@Rollback Ensures that the transaction is rolled back after the test method completes, maintaining the integrity and consistency of the test database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Summary of Repository Unit Testing

A

@DataJpaTest followed by
H2 DB + JUnit

How well did you know this?
1
Not at all
2
3
4
5
Perfectly