How to test Spring Data repositories?

前端 未结 8 1774
隐瞒了意图╮
隐瞒了意图╮ 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

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题