Home > Back-end >  Bean autowired as null for integration test using spring boot 2.1.15.RELEASE(junit 4)
Bean autowired as null for integration test using spring boot 2.1.15.RELEASE(junit 4)

Time:12-01

Following is my code that is causing issue and it is using spring-boot-starter-parent 2.1.15.RELEASE(this version has junit 4 in it).In this context,summary,title all beans are injected as null.

import com.example.demo.helpers.Subtitle;
import com.example.demo.helpers.Summary;
import com.example.demo.helpers.Title;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;

@SpringBootTest(classes = {Summary.class, Title.class, Subtitle.class},webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = org.springframework.boot.test.context.ConfigFileApplicationContextInitializer.class)
public class DemoApplicationTests {

    @Autowired
    ApplicationContext context;  // null

    @Autowired
    Summary summary;    // null

    @Autowired
    Title title;        // null

    @Test
    public void contextLoads() {
        System.out.println("executed testcase..");
    }
}

However when i upgrade the version of spring-boot-starter-parent to 2.6.1(it has junit 5 in it).All autowired beans are getting injected properly.

However there is certain limitation that i can not upgrade version as of now.

CodePudding user response:

You're missing

@RunWith(SpringRunner.class)

Otherwise Autowired doesn't work on JUnit 4

see SpringRunner vs SpringBootTest

  • Related