0
0
JUnittesting~15 mins

@DataJpaTest for repository testing in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify saving and retrieving an entity using @DataJpaTest
Preconditions (3)
Step 1: Create a new User object with name 'Alice'
Step 2: Save the User object using UserRepository
Step 3: Retrieve the User by its id using UserRepository
Step 4: Verify the retrieved User is not null
Step 5: Verify the retrieved User's name is 'Alice'
✅ Expected Result: The User entity is saved and retrieved correctly with the name 'Alice'
Automation Requirements - JUnit 5 with Spring Boot Test
Assertions Needed:
Assert that the retrieved User is not null
Assert that the retrieved User's name equals 'Alice'
Best Practices:
Use @DataJpaTest annotation for repository testing
Use @Autowired to inject the repository
Use @Test annotation for test methods
Use assertThat from AssertJ for readable assertions
Use @Transactional rollback behavior provided by @DataJpaTest
Automated Solution
JUnit
package com.example.demo;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import java.util.Optional;

@DataJpaTest
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void testSaveAndFindUser() {
        // Create a new User
        User user = new User();
        user.setName("Alice");

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

        // Retrieve the User by id
        Optional<User> retrievedUserOpt = userRepository.findById(savedUser.getId());

        // Verify the User is present
        assertThat(retrievedUserOpt).isPresent();

        User retrievedUser = retrievedUserOpt.get();

        // Verify the name is 'Alice'
        assertThat(retrievedUser.getName()).isEqualTo("Alice");
    }
}

// Entity class
package com.example.demo;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

// Repository interface
package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

This test class uses @DataJpaTest to load only the JPA components and an in-memory database for fast testing.

The UserRepository is injected with @Autowired. The test method testSaveAndFindUser creates a new User entity, saves it, and then retrieves it by its generated ID.

Assertions check that the retrieved user exists and that its name matches the expected value 'Alice'.

The entity class User uses JPA annotations for ID generation and mapping.

This setup ensures the repository works correctly with the database layer without loading the full application context.

Common Mistakes - 4 Pitfalls
Not using @DataJpaTest and loading the full Spring context
Not checking if Optional is present before accessing the entity
{'mistake': "Hardcoding IDs instead of using the saved entity's generated ID", 'why_bad': 'IDs are generated by the database and may not be predictable.', 'correct_approach': 'Use the ID returned from the save() method to retrieve the entity.'}
Not using assertions from AssertJ or JUnit and relying on print statements
Bonus Challenge

Now add data-driven testing with 3 different User names to verify saving and retrieving works for each.

Show Hint