Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to annotate the test class for JPA repository testing.
JUnit
@[1] public class UserRepositoryTest { // test methods }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @SpringBootTest which loads the full context instead of a slice for JPA.
Using @WebMvcTest which is for controller layer testing.
✗ Incorrect
The @DataJpaTest annotation is used to configure a test class for JPA repository testing with an embedded database.
2fill in blank
mediumComplete the code to inject the repository into the test class.
JUnit
@Autowired
private [1] userRepository; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Injecting UserService or UserController instead of the repository.
Injecting EntityManager directly without repository.
✗ Incorrect
The repository interface (UserRepository) is injected to test its methods.
3fill in blank
hardFix the error in the test method to save and verify a user entity.
JUnit
@Test
void testSaveUser() {
User user = new User("john", "john@example.com");
userRepository.[1](user);
assertThat(userRepository.findById(user.getId())).isPresent();
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using saveUser which is not a JpaRepository method.
Using persist which is an EntityManager method, not repository.
✗ Incorrect
The correct method to save an entity in JpaRepository is save().
4fill in blank
hardFill both blanks to write a test that finds a user by email.
JUnit
@Test
void testFindByEmail() {
User user = new User("anna", "anna@example.com");
userRepository.save(user);
Optional<User> found = userRepository.[1]("anna@example.com");
assertThat(found.[2]()).isTrue();
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using isEmpty() which checks for absence, not presence.
Using getEmail() which is a getter, not an Optional method.
✗ Incorrect
The repository method findByEmail returns an Optional; isPresent() checks if a value exists.
5fill in blank
hardFill all three blanks to write a test that deletes a user and verifies deletion.
JUnit
@Test
void testDeleteUser() {
User user = new User("mike", "mike@example.com");
userRepository.save(user);
userRepository.[1](user);
Optional<User> deleted = userRepository.[2](user.getId());
assertThat(deleted.[3]()).isFalse();
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using remove() which is not a JpaRepository method.
Asserting isPresent() is true after deletion, which is incorrect.
✗ Incorrect
Use delete() to remove the entity, findById() to check, and isPresent() to verify absence (assert false).