I want a repository (say, UserRepository
) created with the help of Spring Data. I am new to spring-data (but not to spring) and I use this tutorial. My choice o
With Spring Boot + Spring Data it has become quite easy:
@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {
@Autowired
MyRepository subject;
@Test
public void myTest() throws Exception {
subject.save(new MyEntity());
}
}
The solution by @heez brings up the full context, this only bring up what is needed for JPA+Transaction to work. Note that the solution above will bring up a in memory test database given that one can be found on the classpath.
If you're using Spring Boot, you can simply use @SpringBootTest
to load in your ApplicationContext
(which is what your stacktrace is barking at you about). This allows you to autowire in your spring-data repositories. Be sure to add @RunWith(SpringRunner.class)
so the spring-specific annotations are picked up:
@RunWith(SpringRunner.class)
@SpringBootTest
public class OrphanManagementTest {
@Autowired
private UserRepository userRepository;
@Test
public void saveTest() {
User user = new User("Tom");
userRepository.save(user);
Assert.assertNotNull(userRepository.findOne("Tom"));
}
}
You can read more about testing in spring boot in their docs.