Spring REST Docs configuration not working - java.lang.IllegalStateException - java

#AutoConfigureRestDocs and #AutoConfigureMockMvc do not configure MockMvc correctly. Even manually configuring them do not seem to help.
I tried configuring the MockMvc and MockMvcRestDocumentationConfigurer also manually, but it did not help.
This is the current setup:
#RunWith(SpringRunner.class)
#SpringBootTest(properties= "spring.main.allow-bean-definition-overriding=true")
#AutoConfigureRestDocs
#AutoConfigureMockMvc
public class LoginLogoutTest {
#Autowired
private MockMvc mockMvc;
#Test
public void adminCanLoginLogout() throws Exception {
mockMvc.perform(formLogin().user(TestConfig.ADMIN_USERNAME).password(TestConfig.PASSWORD))
.andExpect(status().isOk())
.andExpect(authenticated().withUsername(TestConfig.ADMIN_USERNAME))
.andDo(document("login"));
mockMvc.perform(logout())
.andExpect(status().isOk())
.andExpect(unauthenticated())
.andDo(document("logout"));
}
}
I also tried configuring them with something like this:
#RunWith(SpringRunner.class)
#SpringBootTest(properties= "spring.main.allow-bean-definition-overriding=true")
public class LoginLogoutTest {
#Rule
public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");
private MockMvc mockMvc;
#Before
public void setUp(){
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
#Test
public void adminCanLoginLogout() throws Exception {
mockMvc.perform(formLogin().user(TestConfig.ADMIN_USERNAME).password(TestConfig.PASSWORD))
.andExpect(status().isOk())
.andExpect(authenticated().withUsername(TestConfig.ADMIN_USERNAME))
.andDo(document("login"));
mockMvc.perform(logout())
.andExpect(status().isOk())
.andExpect(unauthenticated())
.andDo(document("logout"));
}
}
I am getting the following error:
java.lang.IllegalStateException: REST Docs configuration not found. Did you forget to apply a MockMvcRestDocumentationConfigurer when building the MockMvc instance?
What am I doing wrong? The error message is not very informative.

Related

MockMvc is null when testing the Web Layer

I have this MvcTest in my application:
#SpringBootTest
#WebMvcTest
public class BarsControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
but when I run the test mockMvc is null when running the tests.
You shouldn't use #WebMvcTest and #SpringBootTest together.
If you want to test both web layer and other layers Use #AutoConfigureMockMvc and #SpringBootTest together:
#SpringBootTest
#AutoConfigureMockMvc
public class BarsControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
Or if you only want to test web layer you can use just #WebMvcTest: note the this does not load full spring application context(It only loads web layer)
#WebMvcTest
public class BarsControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}

Error running JUnitWeb Test on Method setup

I have a Spring application,
and I've created this test:
#RunWith(SpringRunner.class)
#SpringJUnitWebConfig(locations = {
"classpath:testDatabaseContext.xml",
"classpath:testServicesContext.xml",
"classpath:backoffice-servlet.xml"
})
public class UserControllerTests {
#Autowired
private MockMvc mockMvc;
#Before
void setup(WebApplicationContext wac) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
..
}
but when I start the test I got this error:
rg.junit.runners.model.InvalidTestClassError: Invalid test class 'com.pastis.UserControllerTests':
1. Method setup() should be public
2. Method setup should have no parameters
Here an example:
RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(classes = MyWebConfig.class)
public class CustomerControllerTest {
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup () {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
#Test
public void testUserController () throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status()
.isOk();
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/customers");
this.mockMvc.perform(builder)
.andExpect(ok);
}
}
So I explain the output of the exception:
Add the modifier public to your method setup, otherwise JUnit can't invoke it
Remove the parameter from the method, #Before, #After and such don't allow parameters.
How to setup MockMvc correctly is another question. Recent Spring and additional annotations regarding web scope initialization and -behavior leave the scope of this answer. (This also requires more clarification, for example which JDK, which Spring or Spring Boot… XML configuration, dbunit and JUnit 4 suggest a legacy context.)

Spring Boot + TestNG + MockMVC gives Null for #Autowired

I'm new to Spring-Boot, TestNG and MockMVC, when i try to write TestNG test case it gives Null for below:
#Autowired
private WebApplicationContext webApplicationContext;
and also it gives null for
#BeforeTest
public void start()
{
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
Also, based on previous post from stackoverflow by moving
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); to #Test also the problem not resolved.
Below my code snippet
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
#BeforeTest
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void testEmployee() throws Exception {
mockMvc.perform(get("/employee")).andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("emp1")).andExpect(jsonPath("$.designation").value("manager"))
.andExpect(jsonPath("$.empId").value("1")).andExpect(jsonPath("$.salary").value(3000));
}
Any link or working sample shared will be great help.
thanks
If you want to autowire WebApplicationContext, your test class should be annotated with #ContextConfiguration and #WebAppConfiguration.
You can find an example-ish here (Spring Framework's official repository).

How do I wire up the correct Spring context to my Cucumber tests?

I have a working integration test for my Spring Web MVC app that looks like this:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = ShibaApplication.class)
#WebAppConfiguration
public class EchoControllerTests {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
private void setup() throws Exception {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
}
#Test
public void echo() throws Exception {
mockMvc.perform(get("/echo/blargh"))
.andExpect(status().isOk())
.andExpect(content().string("blargh"));
}
}
Leaving that (successful) test in place, I tried to create an identical Cucumber test. The Cucumber runner is:
#RunWith(Cucumber.class)
#CucumberOptions(features="src/test/resources",
glue={"co.masslab.shiba", "cucumber.api.spring"})
public class CucumberTests {
}
The class that defines the Cucumber steps looks like:
#WebAppConfiguration
#Import(ShibaApplication.class)
#ContextConfiguration(classes=CucumberTests.class)
public class WebStepDefs {
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
private ResultActions resultActions;
#When("^the client calls the echo endpoint$")
public void the_client_calls() throws Exception {
Assert.notNull(webApplicationContext);
this.mockMvc = webAppContextSetup(webApplicationContext).build();
this.resultActions = mockMvc.perform(get("/echo/blargh"));
}
#Then("^the client receives a status code of 200$")
public void the_client_receives_a_status_code() throws Exception {
resultActions.andExpect(status().isOk());
}
}
However, the cucumber test fails, as the result is not a 200 but a 404.
I suspect this is because the WebApplicationContext getting autowired into the WebStepDefs class isn’t the same as the one that gets autowired into the EchoControllerTests. I’ve been going over the Spring JavaConfig Reference Guide v1.0.0.M4, but I haven’t yet figured out where I’m going wrong.
I kept trying different combinations of annotations, and finally figured this one out. The annotations for WebStepsDef that worked for me were:
#ContextConfiguration(classes=ShibaApplication.class, loader=SpringApplicationContextLoader.class)
#IntegrationTest
#WebAppConfiguration

Is it possible to observe MockMvc tests with Fiddler?

I am testing my web-app with
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = MyApp.class)
//#WebAppConfiguration
#WebIntegrationTest
public class MyTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
}
#Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
#Test
public void someTest() throws Exception {
result = mockMvc.perform(get("/user/"));
result
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
...
}
Is it possible to observe how tests run with Filler? Or it sends without network? Is it possible to force MockMvc to use network?
Currently I see nothing in Fiddler.
Setting of
System.getProperties().put("http.proxyHost", "127.0.0.1");
System.getProperties().put("http.proxyPort", "8888");
didn't help.

Categories

Resources