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

Testing using spring boot throws null pointer exception

我是 spring 引导新手,我正在尝试测试一个非常简单的 class。但是当我 运行 下面的 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 调用中自动装配。但是 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 中。