Java @DataJpaTest中的存储库已初始化为null
我试图在我的spring boot应用程序中为存储库编写一些测试,但是存储库自动连接为null。测试类的代码如下所示:Java @DataJpaTest中的存储库已初始化为null,java,spring-boot,junit,spring-data-jpa,spring-test,Java,Spring Boot,Junit,Spring Data Jpa,Spring Test,我试图在我的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.Enable
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测试的形式运行这个文件时,print语句会被打印出来,这会确认随后出现的nullpointerexception。我的所有测试都与主应用程序在同一个包中,但这些包都在src/test/java下。我尝试了一些包装名称的改变,但没有帮助,所以我不知道现在的问题是什么。为什么repo被初始化为null?下面是一个使用@DataJpaTest和TestEntityManager进行单元测试的工作示例: PersonRepo扩展了JpaRepository并具有@Repository注释 我在我的项目中使用这种方法,若所有配置都有效并且应用程序可以正常运行,测试将通过
@RunWith(SpringRunner.class)
@DataJpaTest
public class RepositoryTest {
@Autowired
TestEntityManager entityManager;
@Autowired
PersonRepo sut;
@Test
public void some_test() {
Person toSave = new Person();
toSave.setPersonId(23);
entityManager.persistAndFlush(toSave);
Person getFromDb = sut.findOne(23);
Assert.assertTrue(getFromDb.getPersonId() == 23);
}
}
当使用测试切片(如@DataJpaTest时,问题是Spring引导只会加载一组特定的类。请参阅Spring文档中的此部分: @如果要测试JPA应用程序,可以使用DataJpaTest。默认情况下,它将配置内存中的嵌入式数据库,扫描@Entity类并配置SpringDataJPA存储库。常规@Component bean将不会加载到ApplicationContext中 @存储库被视为常规的@组件,因为它不是Spring数据JPA存储库(接口为)。因此,它没有加载。默认情况下,仅加载存储库接口,如下所示:
public interface PersonRepo extends JpaRepository<Person, Long> {
...
}
或者只需将所需的@Repository类导入测试:
@Import(PersonRepo.class)
这里还有另一个类似的问题:我想一旦personRepoTest为空,您就需要返回吗?由于您的
if
条件将执行,但行personRepoTest.save(toSave)
似乎是NullPointerException。@gtgaxiola print语句只是为了确认它是null,但问题是为什么它是null(编辑问题以更好地反映这一点)?为什么不使用@RunWith(SpringRunner.class)@DataJpaTest
?@DirkDeyne我以前有过,但是我得到的无法加载ApplicationContext
error@ITWorker是的……请注意,上面的testclass缺少@RunWith(SpringRunner.class)
在发布问题之前,我尝试了这种方法,但没有成功(关于需要在主应用程序中自动连接的服务的错误)。我的应用程序有一个调度程序,因此我遵循此so线程作为我尝试的基础:嗨,你能帮我解决这个问题吗
@Import(PersonRepo.class)