Bird
Raised Fist0
JUnittesting~20 mins

@DataJpaTest for repository testing in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
DataJpaTest Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the test execution result of this @DataJpaTest?
Consider this JUnit test using @DataJpaTest for a Spring Data JPA repository. What will be the test result?
JUnit
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void testSaveAndFind() {
        User user = new User(null, "Alice");
        userRepository.save(user);
        User found = userRepository.findByName("Alice");
        assertThat(found).isNotNull();
        assertThat(found.getName()).isEqualTo("Alice");
    }
}
ATest passes because the user is saved and found correctly in the in-memory database.
BTest fails with NullPointerException because userRepository is not injected.
CTest fails with DataIntegrityViolationException due to missing @Transactional annotation.
DTest fails because @DataJpaTest disables repository beans by default.
Attempts:
2 left
💡 Hint
Remember that @DataJpaTest configures an in-memory database and injects repository beans automatically.
❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies the repository returns no users initially?
Given a UserRepository with method findAll(), which assertion correctly checks that the repository is empty before any save?
JUnit
import static org.junit.jupiter.api.Assertions.*;

List<User> users = userRepository.findAll();
AassertNotNull(users); assertEquals(0, users.size());
BassertEquals(null, users);
CassertTrue(users.isEmpty());
DassertFalse(users.isEmpty());
Attempts:
2 left
💡 Hint
Check if the list returned by findAll() contains any elements.
🔧 Debug
advanced
2:30remaining
Why does this @DataJpaTest fail with NoSuchBeanDefinitionException?
This test fails with NoSuchBeanDefinitionException for UserRepository. What is the likely cause?
JUnit
@DataJpaTest
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void testFind() {
        User user = userRepository.findByName("Bob");
        assertNull(user);
    }
}
AUserRepository interface is missing @Repository annotation.
BThe test class is missing @SpringBootTest annotation to load the full context.
CThe test method is missing @Transactional annotation.
DUserRepository is not in the same package or a subpackage of the test class, so it is not scanned.
Attempts:
2 left
💡 Hint
Check the package structure and component scanning rules of @DataJpaTest.
🧠 Conceptual
advanced
1:30remaining
What is the default database used by @DataJpaTest?
When running a test annotated with @DataJpaTest without any database configuration, which database is used by default?
AAn embedded in-memory H2 database
BThe production MySQL database configured in application.properties
CAn embedded in-memory Derby database
DNo database is used; repositories are mocked automatically
Attempts:
2 left
💡 Hint
Spring Boot auto-configures an embedded database for tests if available.
❓ framework
expert
2:30remaining
Which annotation combination ensures @DataJpaTest rolls back transactions after each test?
You want each test method in a @DataJpaTest class to run in a transaction that rolls back after the test completes. Which annotation setup achieves this?
A@DataJpaTest with @Commit to commit transactions after tests
B@DataJpaTest alone (default rollback behavior enabled)
C@DataJpaTest with @Transactional(propagation = Propagation.NOT_SUPPORTED)
D@DataJpaTest with @Rollback(false) to disable rollback
Attempts:
2 left
💡 Hint
Check the default transaction behavior of @DataJpaTest.

Practice

(1/5)
1. What is the primary purpose of using @DataJpaTest in Spring Boot testing?
easy
A. To perform integration testing with external APIs
B. To test the entire Spring Boot application including web layers
C. To test only the service layer without database access
D. To test only the JPA repositories with an in-memory database setup

Solution

  1. Step 1: Understand the role of @DataJpaTest

    @DataJpaTest is designed to test JPA repositories specifically, setting up only database-related components.
  2. Step 2: Recognize the default database setup

    It uses an in-memory database by default to keep tests fast and isolated.
  3. Final Answer:

    To test only the JPA repositories with an in-memory database setup -> Option D
  4. Quick Check:

    @DataJpaTest = repository testing with in-memory DB [OK]
Hint: Remember @DataJpaTest focuses on repositories only [OK]
Common Mistakes:
  • Thinking it tests the whole application
  • Confusing it with @SpringBootTest
  • Assuming it tests service or controller layers
2. Which annotation is NOT typically used together with @DataJpaTest for repository testing?
easy
A. @AutoConfigureTestDatabase
B. @SpringBootTest
C. @Transactional
D. @MockBean

Solution

  1. Step 1: Identify annotations used with @DataJpaTest

    @DataJpaTest automatically includes @Transactional and often uses @AutoConfigureTestDatabase to control DB setup.
  2. Step 2: Understand @SpringBootTest role

    @SpringBootTest loads the full application context, which is not typical with @DataJpaTest that loads a slice for repositories.
  3. Final Answer:

    @SpringBootTest -> Option B
  4. Quick Check:

    @DataJpaTest excludes full context, so no @SpringBootTest [OK]
Hint: Full app context uses @SpringBootTest, not @DataJpaTest [OK]
Common Mistakes:
  • Using @SpringBootTest with @DataJpaTest unnecessarily
  • Confusing @MockBean usage in repository tests
  • Ignoring transactional rollback behavior
3. Given the following test code snippet using @DataJpaTest:
@DataJpaTest
public class UserRepositoryTest {
  @Autowired
  private UserRepository userRepository;

  @Test
  void testSaveAndFind() {
    User user = new User(null, "Alice");
    userRepository.save(user);
    Optional<User> found = userRepository.findByName("Alice");
    assertTrue(found.isPresent());
  }
}
What will be the test result when executed?
medium
A. Test fails due to missing @Transactional annotation
B. Test fails because the database is not initialized
C. Test passes because the user is saved and found correctly
D. Test fails because userRepository is null

Solution

  1. Step 1: Analyze @DataJpaTest behavior

    @DataJpaTest sets up an in-memory database and configures repositories automatically with transactional rollback.
  2. Step 2: Check test logic

    The test saves a user and then finds it by name. Since the repository is autowired and database is in-memory, the user will be found.
  3. Final Answer:

    Test passes because the user is saved and found correctly -> Option C
  4. Quick Check:

    Save + find with @DataJpaTest = pass [OK]
Hint: In-memory DB + @DataJpaTest means save/find works in tests [OK]
Common Mistakes:
  • Assuming database is empty or uninitialized
  • Forgetting @DataJpaTest provides @Transactional by default
  • Thinking repository needs manual initialization
4. Consider this test class using @DataJpaTest:
@DataJpaTest
public class ProductRepositoryTest {
  @Autowired
  private ProductRepository productRepository;

  @Test
  void testFindById() {
    Product product = new Product(1L, "Book");
    productRepository.save(product);
    Product found = productRepository.findById(1L).orElse(null);
    assertNotNull(found);
  }
}
The test fails with an AssertionError on assertNotNull(found). What is the most likely cause?
medium
A. The Product entity is missing an @Entity annotation
B. The productRepository is not autowired correctly
C. The save method does not persist the entity in @DataJpaTest
D. The test method is missing @Transactional annotation

Solution

  1. Step 1: Check entity configuration

    If the Product class lacks @Entity, JPA won't map it, so save won't persist anything.
  2. Step 2: Understand repository autowiring and transactions

    @DataJpaTest autowires repositories and runs tests in transactions by default, so these are unlikely causes.
  3. Final Answer:

    The Product entity is missing an @Entity annotation -> Option A
  4. Quick Check:

    Missing @Entity means no persistence [OK]
Hint: Always check @Entity on classes for JPA persistence [OK]
Common Mistakes:
  • Assuming @Transactional is missing in @DataJpaTest
  • Thinking save() doesn't work in tests
  • Ignoring entity annotations
5. You want to test a custom query method in your repository using @DataJpaTest. The method returns a list of users with age greater than a given value. Which of the following is the best practice to ensure your test is reliable and isolated?
hard
A. Use @DataJpaTest with an in-memory database and insert test users before querying
B. Use @SpringBootTest and connect to the production database for real data
C. Mock the repository method using @MockBean and verify the return values
D. Write the test without inserting data, assuming the database has users

Solution

  1. Step 1: Understand test isolation with @DataJpaTest

    @DataJpaTest uses an in-memory database that starts empty for each test, so you must insert test data.
  2. Step 2: Avoid external dependencies and mocks for repository tests

    Using production DB or mocks defeats the purpose of repository testing with real JPA behavior.
  3. Final Answer:

    Use @DataJpaTest with an in-memory database and insert test users before querying -> Option A
  4. Quick Check:

    Insert test data in @DataJpaTest for reliable queries [OK]
Hint: Always insert test data in @DataJpaTest for accurate results [OK]
Common Mistakes:
  • Connecting to production DB in tests
  • Relying on existing data without setup
  • Mocking repository methods instead of real queries
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard