简体   繁体   中英

Testing using spring boot throws null pointer exception

I am new to spring boot and i am trying to test a very simple class. But when i run the testMe() below I get exception below

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)

My understanding is when the context is loaded all the beans are initialized and object HelloWorld is created and are autowired in MyTest call. But helloWorld object is null at line helloWorld.printHelloWorld();

I need assistance here to understand what is missing.

@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;
    }
}

You're running your tests with a runner that's not Spring-aware, so no wiring is happening. Look at the Spring Boot testing documentation , all their examples use @RunWith(SpringRunner.class) . To mock a bean, annotate it with @MockBean , not @Mock . Make sure that the spring-boot-starter-test is included in your POM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM