Spring Boot offers a simple annotation @DataJpaTest for data layer unit tests. A simple example is listed as follows:
@DataJpaTest
@RunWith(SpringRunner.class)
public class UserRepositoryTest {
@Autowired
UserRepository userRepository;
@Autowired
TestEntityManager entityManager;
//Test Methods
}
@DataJpaTest may also inject a TestEntityManager bean, which provides an alternative to the standard JPA entityManager specifically designed for tests.
If you want to use TestEntityManager outside of @DataJpaTest, you can also use the @AutoConfigureTestEntityManager annotation.
Data JPA tests are run against an embedded database by default. This ensures that tests can be run as many times as you would want without affecting the database.