【发布时间】:2019-01-09 10:49:48
【问题描述】:
我正在尝试在我的 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 测试运行时,打印语句确实会打印出来,这确认了随后出现的 nullpointerexception。我所有的测试都在与主应用程序相同的包中,但这些包位于 src/test/java 下。我尝试对包装名称进行一些更改,但这没有帮助,所以我不知道现在是什么问题。为什么repo初始化为null?
【问题讨论】:
-
我认为你需要在 personRepoTest 为空时返回?由于您的
if条件将执行,而且personRepoTest.save(toSave)行似乎是NullPointerException。 -
@gtgaxiola print 语句只是为了确认它为空,但问题是它为什么为空(编辑问题以更好地反映这一点)?
-
你为什么不用
@RunWith(SpringRunner.class) @DataJpaTest? -
@DirkDeyne 我以前有过,但我收到了
Failed to load ApplicationContext错误 -
@ITWorker 是的...请注意上面的测试类缺少
@RunWith(SpringRunner.class)
标签: java spring-boot junit spring-data-jpa spring-test