등록일:2020-01-17 14:21:40 (0%) 작성자: 제목:SpringBoot unit test autowired field NullPointerException
SpringBoot unit test autowired field NullPointerException
Introduction
This post would demo how to solve the NullPointerException when using springboot unit testing.
Environments
SpringBoot 1.5.9
Java 1.8
Class under test
This is the class under test, it’s just a simple class.
As you can see, this class uses the StringLengther to get the string length.
The unit test code
As you can see, we use a @Test annotation to test the lambdaCUT’s s1 method, And the lambdaCUT instance is @Autowired by the spring container.
Problem occurring
Now run the unit test, you can see the result:
Problem debugging
We can debug the problem by adding a breakpoint at the line of the problem, and rerun it,we would got this:
we can see that the root cause is the lambdaCUT property is null, but we @Autowired it! The autowire process must be disabled by some reason.
Problem solving
After debugging, we found that the root cause is the @Autowire not working, and we found that the UnitTest is a common junit test case, and is not a springboot testcase, so there is no spring container for it. This is the root cause, And then, we change the code like this:
rerun the test, and we got this:
You can find detail documents about the springboot and unit testing here: