How to test Spring Data repositories?

前端 未结 8 1817
隐瞒了意图╮
隐瞒了意图╮ 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 15:57

    With JUnit5 and @DataJpaTest test will look like (kotlin code):

    @DataJpaTest
    @ExtendWith(value = [SpringExtension::class])
    class ActivityJpaTest {
    
        @Autowired
        lateinit var entityManager: TestEntityManager
    
        @Autowired
        lateinit var myEntityRepository: MyEntityRepository
    
        @Test
        fun shouldSaveEntity() {
            // when
            val savedEntity = myEntityRepository.save(MyEntity(1, "test")
    
            // then 
            Assertions.assertNotNull(entityManager.find(MyEntity::class.java, savedEntity.id))
        }
    }
    

    You could use TestEntityManager from org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager package in order to validate entity state.

提交回复
热议问题