使用 spring boot 测试抛出空指针异常

Neh*_*eha 4 java spring spring-boot spring-boot-test

我是 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)
Run Code Online (Sandbox Code Playgroud)

我的理解是,当加载上下文时,所有 bean 都被初始化,对象HelloWorld被创建并在MyTest调用中自动装配。但是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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Dog*_*027 5

您正在使用不支持 Spring 的运行器运行测试,因此不会发生任何接线。查看Spring Boot 测试文档,他们所有的示例都使用@RunWith(SpringRunner.class). 要模拟 bean,请使用 注释@MockBean,而不是@Mock。确保spring-boot-starter-test包含在您的 POM 中。