【发布时间】:2017-03-10 15:53:34
【问题描述】:
我想在所有测试之前在我的数据库中插入一次。这就是我在 setUp() 方法中尝试做的事情。但是得到了空指针。 Spring Boot 版本是 1.5.1.RELEASE。有任何想法吗? 这是来自我的测试课:
@Autowired
private static UserRepository userRepository;
@BeforeClass
public static void setUp() {
User user = User.
.builder()
.id(10)
.name("John")
.build();
userRepository.deleteAll(); //NullPointerException at this step
userRepository.save(user);
}
这是我的实体类:
@Entity
@Table(schema="test", name = "TBL_USERS")
@AllArgsConstructor
@Builder
@Data public class User implements Persistable<String>{
@Id
@Column(name = "ID", columnDefinition = "decimal")
private String id;
@Column(name = "NAME", columnDefinition = "char", nullable = false)
private String name;
...
}
这是界面:
public interface UserRepository extends JpaRepository<User, String> {}
堆栈跟踪:
java.lang.NullPointerException
at com.company.myapp.get.GetUserTest.setUp(GetUserTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
【问题讨论】:
-
注入不适用于
static参数,因此永远不会注入,即使它被允许也不会在@BeforeClass中可用。 -
好的。那么在这种情况下,@BeforeClass 的合适替代品是什么?
标签: spring-boot junit nullpointerexception automated-tests