我是 Spring Boot 的新手,我正在尝试测试一个非常简单的类。但是当我运行 testMe()
下面我在下面得到异常
java.lang.NullPointerException
at MyTest.testMe(MyTest.java:25)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
我的理解是,当上下文加载时,所有 bean 都被初始化,对象
HelloWorld
在 MyTest
中创建并 Autowiring 称呼。但是helloWorld
对象是 null
在线 helloWorld.printHelloWorld();
我需要帮助来了解缺少什么。
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = {AppConfigTest.class})
public class MyTest {
@Mock
@Autowired
private Message myMessage;
@Autowired
private HelloWorld helloWorld;
@Test
public void testMe(){
helloWorld.printHelloWorld();
}
}
@Configuration
public class AppConfigTest {
@Bean
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
@Bean
public Message getMessage(){
return new Message("Hello");
}
}
public interface HelloWorld {
void printHelloWorld();
}
public class HelloWorldImpl implements HelloWorld {
@Autowired
Message myMessage;
@Override
public void printHelloWorld() {
System.out.println("Hello : " + myMessage.msg);
}
}
public class Message {
String msg;
Message(String message){
this.msg = message;
}
}
最佳答案
您正在使用不支持 Spring 的运行器运行测试,因此不会发生任何接线。看Spring Boot testing documentation ,他们所有的例子都使用 @RunWith(SpringRunner.class)
.要模拟 bean,请使用 @MockBean
对其进行注释。 ,不是 @Mock
.确保 spring-boot-starter-test
包含在您的 POM 中。
关于java - 使用 spring boot 测试抛出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51387030/