Hary
Hary

Reputation: 1217

WebApplicationContext is always null in a spring boot test

My test class looks like this

@SpringBootTest(webEnvironment=WebEnvironment.MOCK)
public class sampleClassTest{

  @Autowired
  private WebApplicationContext wac;
}

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

}

In the setup method, wac is always null. From spring boot documentation, @SpringBootTest(webEnvironment=WebEnvironment.MOCK) always created a mock WebapplicaitonContext.

So I would expect it get autowired in the code above which doesn't happen.

Can someone tell me how to go about creating a webapplicationContext in this case so that it's not null like in my case ?

UPDATE

I am running spring boot tests invoking them from a class with springboot annotation.

Both test (springboottest) and calling class (springboot) application are in the same spring boot project under src/main/java.

I have nothing under src/main/test. I have done in this way because if classes from src/main/java want to call a test class then, it isn't really a test class.

Now, the problem is that I can't use runWith(SpringRunner.class) in springbootTest class. If I did that to get a mock webApplicationContext then, it gives me this error:

 javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication

I am not sure how to do about this.

Upvotes: 1

Views: 6030

Answers (3)

Mr.Mountain
Mr.Mountain

Reputation: 883

If someone is struggling with this issue in 2022 - please keep my defined precondions in mind. If you are using @SpringBootTest with defined port and constructor auto-wiring of the test class, the application context might be null.

It seems that the constructor dependency injection is eager and the cache aware context delegate of Spring is searching for a web application context which is no available yet. If you use field auto-wiring your test might run in a deterministic manner.

Upvotes: 1

Dhruv Kumar Sood
Dhruv Kumar Sood

Reputation: 25

Whoever is facing this issue, make sure your spring boot starter parent version is compatible with spring cloud version in pom.xml

I was facing same issue, i resolved it by doing same.

Upvotes: 0

Andy Wilkinson
Andy Wilkinson

Reputation: 116031

To use @SpringBootTest you need to use Spring Framework's test runner. Annotate your test class with @RunWith(SpringRunner.class).

Upvotes: 1

Related Questions