@Autowired Bean is NULL in Spring Boot Unit Test

I am new to JUnit and automated testing and really want to get into automating my tests. This is a Spring Boot application. I have used Java Based Annotation style instead of XML based configuration.

I have a test class in which I'd like to test a method which retrieves a response based on a users' input.

Testing class:

public class SampleTest(){

  private SampleClass sampleClass;

  public void testInput(){

  String sampleInput = "hi";

  String actualResponse = sampleClass.retrieveResponse(sampleInput);

  assertEquals("You typed hi", actualResponse);


Inside my "SampleClass" I have autowired a bean like this.

private OtherSampleClass sampleBean;

Inside my "OtherSampleClass" I have annotated a method like so:

@Bean(name = "sampleBean")
public void someMethod(){

The issue I'm having is when I try to run the test without the @RunWith and @SpringBootTest annotations when I try to run the test my variables annotated @Autowired are null. And when I try to run the test with those annotations RunWith & SpringBootTest then I get an

IllegalStateException caused by BeanCreationException: Error creating bean with name "sampleBean" AND failure to load application context caused by BeanInstantiationException.

The code works 'properly' when I try to use it as a user would so I can always test this way but I think automated tests would be good for the longevity of the program.

I have used the Spring Boot Testing Docs to assist me in this.

The following config works for me.

File: build.gradle


File: MYServiceTest.java

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MYServiceTest {

    private MYService myService;

    public void test_method() {

SpringBoot unit test autowired field NullPointerException, SpringBoot unit test autowired field NullPointerException see that the root cause is the lambdaCUT property is null, but we @Autowired it! Now run the unit test, you can see the result: java.lang.NullPointerException at TestLambdas.test3(TestLambdas.java:45) 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

It's best to keep Spring out of your unit tests as much as possible. Instead of Autowiring your bean just create them as a regular object

OtherSampleClass otherSampleClass = mock(OtherSampleClass.class);
SampleClass sampleClass = new SampleClass(otherSampleClass);

But for this you need to use the Constructor injection instead of Field Injection which improves testability.

Replace this

private OtherSampleClass sampleBean;

With this

private OtherSampleClass sampleBean;

public SampleClass(OtherSampleClass sampleBean){
    this.sampleBean = sampleBean;

Take a look at this answer for an other code example

Two reasons why your Spring @Autowired component is null, Basically, Spring is going to scan the project's classpath (or paths you specified), find all of the @Component classes and make them available for auto-wiring. So if you forget to annotate a class it will not be auto-wired and when you try and use it you will get a null and a NullPointerException . So, why this article when we shouldn’t use Spring Boot in a unit test? To be honest, most of this tutorial is about writing unit tests without Spring Boot. Creating a Testable Spring Bean. However, there are some things we can do to make our Spring beans better testable. Field Injection is Evil. Let’s start with a bad example.

No need to inject (@Autowired private SampleClass sampleClass;) your actual class which you are testing, and remove SpringBootTest annotation, SpringBootTest annotation used for integration test cases. find the following code will help you.

public class SampleTest(){

  private SampleClass sampleClass;

Spring boot test autowired null, @MockBean in unit testing. Starting with Spring Boot 1 MVC Slice With @ Autowired MockMvc. We will create maven type project and generating JAR build . 5. Unit Testing the Spring Boot Application. Spring boot offers a great class to make testing easier: @SpringBootTest annotation. This annotation can be specified on a test class that runs Spring

Why in the world is my Spring @Autowired Null?, If you're encountering @Autowired instances being null only in unit tests: Check your load orders. I've had lots of problemscaused by conflicts between Spring and Powermock. Make sure you're always instantiating instances inside of methods instead of the class body or test constructor. I'm attempting to create unit tests for a rest service in my spring servlet. But when the controller object is created by @autowire, then all of its @autowired fields are null. My test class is as

Unit Testing with Spring Boot, In this tutorial we'll learn how to build testable Spring beans and get to know the tools that Spring Boot by default imports for writing maintainable unit tests. This test takes about 4.5 seconds to run on an empty Spring project on my application only to autowire a RegisterUseCase instance into our test. It indicates one or more configuration classes to import into application context or spring test context. @Bean definitions declared in imported @TestConfiguration classes should be accessed by using @Autowired injection. Either the bean itself can be autowired, or the configuration class instance declaring the bean can be autowired.

Why is my Spring @Autowired field null?, I have a Spring @Service class (MileageFeeCalculator) that has an that has an @Autowired field (rateService), but the field is null when I try to use it. make sure your class in which @Autowiring is done is a spring bean. method stub System.out.println("test"); ApplicationContext ctx=new java � mvc� Spring uses component scanning to find the classes that it needs to auto-wire and insert into classes for IoC. Basically, Spring is going to scan the project’s classpath (or paths you specified), find all of the @Component classes and make them available for auto-wiring.

  • Please add your SampleClass.
  • Methods annotated with @Bean should return an object, namely the new Spring Bean.
  • Spring injects your autowired beans. If you don't run with the spring runner there's nothing there to inject things so the members remain at their default values (null). Please show more of the exception when you run with spring. It's likely a classpath or property-not-found fail as the root cause.
  • Testing with mock objects is not ideal thing. With spring boot test and modern testing frameworks rest-assured,spring web clients..it is not required to mock things, And top of the question regarding why auto-wiring not working, not about how to test classes.
  • @Yogi This is true in case you are testing controllers, making Integration tests and E2E tests, but for unit tests you should avoid spring as much as possible because it creates much overhead
  • How is this supposed to be an answer to a question that is about how to do @Autowired?