1
votes

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.

2
Add @WebAppContext to the test case. However you can also simply @Autowire the MockMvc class with Spring Boot ( you don't need to create it manually).M. Deinum
I still need a webApplicationContext to register beans in to. So my main problem is to get a webApplicationContext.Hary

2 Answers

1
votes

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

0
votes

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.