How to test Spring Data repositories?

前端 未结 8 1819
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 15:41

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

8条回答
  •  时光说笑
    2020-11-29 16:00

    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.

提交回复
热议问题