How to make instance of CrudRepository interface during testing in Spring?

后端 未结 4 1002
旧时难觅i
旧时难觅i 2021-02-07 08:53

I have a Spring application and in it I do not use xml configuration, only Java Config. Everything is OK, but when I try to test it I faced problems wi

4条回答
  •  太阳男子
    2021-02-07 09:03

    If you're using Spring Boot, you can simplify these approaches a bit by adding @SpringBootTest to load in your ApplicationContext. 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.

提交回复
热议问题