Unit test autowired field NullPointerException
Introduction
This post demonstrates how to resolve the NullPointerException issue 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, and you can see the result:
Problem debugging
We can debug the problem by adding a breakpoint at the line of the problem and rerunning it. We would get this:
We can see that the root cause is the lambdaCUT property being null, even though we @Autowired it! The autowire process must be disabled for some reason.
Problem resolving
After debugging, we found that the root cause is the @Autowired not working, and we discovered that the unit test is a common JUnit test case, not a SpringBoot test case. Therefore, there is no Spring container for it. This is the root cause. We then changed the code like this:
Rerun the test, and we get this:
Summary
In this post, we explored how to resolve the NullPointerException
issue when using SpringBoot unit testing. The key takeaway is to ensure that your unit test class is annotated with @RunWith(SpringRunner.class)
and @SpringBootTest
to enable the Spring context and dependency injection. By doing so, the @Autowired
fields will be properly initialized, and the test will run as expected. This approach is essential for integrating SpringBoot features into your unit tests.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!