我正在尝试在 Spring Boot 应用程序中为存储库编写一些测试,但是存储库自动连接为null。测试类的代码如下:
package jpa.project.repo;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ContextConfiguration;
import jpa.project.entity.Person;
@EnableAutoConfiguration
@ContextConfiguration(classes = PersonRepo.class)
@DataJpaTest
public class PersonRepoTest {
@Autowired
private PersonRepo personRepoTest;
@Test
public void testPersonRepo() throws Exception {
Person toSave = new Person();
toSave.setPersonId(23);
if (personRepoTest == null) {
System.out.println("NULL REPO FOUND");
}
personRepoTest.save(toSave);
Person getFromDb = personRepoTest.findOne(23);
Assert.assertTrue(getFromDb.getPersonId() == 23);
}
}
当我在 Eclipse 中将这个文件作为 JUnit 测试运行时,打印语句确实被打印出来,这证实了随后出现的空指针异常。我的所有测试都与主应用程序位于相同的包中,但包位于 src/test/java 下。我尝试了一些包装名称的更改,但这没有帮助,所以我不知道现在的问题是什么。为什么存储库被初始化为空?
使用测试切片时出现的问题@DataJpaTestSpring Boot 只会加载一组特定的类。请参阅 Spring 文档中的这一部分:
如果您想测试 JPA 应用程序,可以使用 @DataJpaTest。默认情况下,它将配置内存中的嵌入式数据库,扫描 @Entity 类并配置 Spring Data JPA 存储库。常规@Component bean不会被加载到ApplicationContext中。
A @存储库被认为是常规的@成分因为它不是 Spring Data JPA 存储库(接口是)。所以,它没有加载。默认情况下只会加载存储库接口,如下所示:
public interface PersonRepo extends JpaRepository<Person, Long> {
...
}
要解决您的问题,您可以强制@DataJpaTest加载你们所有人@存储库课程:
@DataJpaTest(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Repository.class))
或者只需将您需要的 @Repository 类导入到测试中:
@Import(PersonRepo.class)
这是另一个类似的问题:使用 @DataJpaTest 的 Spring 测试无法使用 @Repository 自动装配类(但使用接口存储库可以!) https://stackoverflow.com/questions/48347088/spring-test-with-datajpatest-cant-autowire-class-with-repository-but-with-in/48347423#48347423
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)