Getting Exception when Trying to run Spring Boot Web test cases. Excpetions : java.lang.NoClassDefFoundError: AsyncRequestTimeoutException - spring

In Setup method when I am attaching Rest Controller Advice to mock mvc then below exception is thrown
java.lang.NoClassDefFoundError: org/springframework/web/context/request/async/AsyncRequestTimeoutException
#RunWith(MockitoJUnitRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AccountDetailsControllerTest {
#Mock
private AccountDetailService accountDetailService;
private MockMvc mockMvc;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc = standaloneSetup(new
AccountDetailsController(accountDetailService))
.setControllerAdvice(new ExceptionControllerAdvice())
.build();
}
}

Thanks all, It was issue with Spring dependency. I was using version of 4.3.1 of spring-web and spring boot 1.5.7 expects 4.3.11.

Related

spring boot: how to configure autowired WebTestClient

Are there any properties available in Spring Boot to configure the #Autowired WebTestClient? For instance, how to set the servlet context path (or just some base path for that matter) on WebTestClient?
Here's how my web tests are configured now:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
#ActiveProfiles("test")
public class MyTestClass{
#Autowired
private WebTestClient cl;
//the rest of it
}
In other words, what is Spring Boot equivalent of
WebTestClient client = WebTestClient.bindToServer()
.baseUrl("http://localhost:<random port>/myServletContext").build();
I didn't find anything useful in documentation:
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
building webTestClient using current application context, no need to hardcode uri and port number
#Autowired
ApplicationContext context;
#Autowired
WebTestClient webTestClient;
#Before
public void setup() throws Exception {
this.webTestClient = WebTestClient.bindToApplicationContext(this.context).build();
}
You can use something like server.servlet.context-path=/myServletContextPath.

#WebMvcTest for SOAP?

Is the Spring Boot annotation #WebMvcTest only intended for sliced RestController tests or should SOAP Endpoints be testable with it too?
When I setup my test and run it, I only get a 404 response as if the endpoint wasn't there so I assume it isn't part of the WebMvc slice.
#RunWith(SpringRunner.class)
#WebMvcTest(value = IdServerPortTypeV10.class)
#Import({SecurityConfig.class, ModelMapperConfig.class, WebServiceConfig.class, ControllerTestBeans.class})
public class AccountEndpointTests {
#Autowired
IdServerPortTypeV10 soapEndpoint;
...
#Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.apply(springSecurity())
.build();
}
#Test
#WithMockUser(roles = VALID_ROLE)
public void getAccountTest_Success() throws Exception {
mockMvc.perform(
post("/soap/idserver/1.0")
.accept(MediaType.TEXT_XML_VALUE)
.headers(SoapTestUtility.getHeader(SERVICE.getNamespaceURI(), "getAccount"))
.content(SoapTestUtility.getAccountXml())
).andDo(print())
.andExpect(status().isOk());
}
}
The endpoint is enabled in WebServiceConfig.class in which #EnableWs is set.
#WebMvcTest is, as the name implies, only for Spring MVC related tests.
Spring's SOAP support is from the Spring Web Services project which has its own integration testing support.

How to mock autowired dependencies in Spring Boot MockMvc Unit tests?

I am expanding upon the basic Spring Boot examples, adding an "autowired" repository dependency to my controller. I would like to modify the unit tests to inject a Mockito mock for that dependency, but I am not sure how.
I was expecting that I could do something like this:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = MockServletContext.class)
#WebAppConfiguration
public class ExampleControllerTest {
private MockMvc mvc;
#InjectMocks
ExampleController exampleController;
#Mock
ExampleRepository mockExampleRepository;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(new ExampleController()).build();
}
#Test
public void getExamples_initially_shouldReturnEmptyList() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/example").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("[]")));
}
}
but it doesn't inject the mock into the MockMvc. Can anyone explain how to do this with #Autowired dependencies, rather than constructor arguments?
Please use #RunWith(MockitoJUnitRunner.class) instead of #RunWith(SpringJUnit4ClassRunner.class)
and you have to use the ExampleController exampleController; field with the injected mocks instead of creating a new one in line mvc = MockMvcBuilders.standaloneSetup(new ExampleController()).build();

Null Service while running JUnit test with Spring

I am developing a JUnit test into a Spring Controller, the Controller calls a bunch of Services. My JUnit test code is above:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {WebApplicationConfiguration.class, DatabaseConfiguration.class, ServiceConfiguration.class})
#WebAppConfiguration
public class ProcessFileControllerTest {
private MockMvc mockMvc;
#Test
public void getPageTest() throws Exception{
final ProcessFileController controller = new ProcessFileController();
SecurityHelperUtility.setupSecurityContext("user", "pass", "ROLE_ADMIN");
mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get(URI.create("/processFile.html")).sessionAttr("freeTrialEmailAddress", "")).andExpect(view().name("processFile"));
}
When I run the JUnit test, I get a NullPointerExcelption when I call this particular line of code of my ProcessFileController.java
final Company company = companyService.getCompanyByUser(userName);
I can see that the Serviceis Null.
In my ProcessFileController.java the Service is being declared as:
#Autowired
private CompanyService companyService;
Any clue? Thanks in advance.
You are creating your controller using the new keyword. It should be a spring managed bean for spring to inject its dependencies. Use #Autowired
#Autowired
ProcessFileController controller;

spring-restdocs is not recognizing apply()

I am trying to generate a Rest API documentation based on spring-restdocs
In following code I am getting a compile time error at apply()
The method apply(RestDocumentationMockMvcConfigurer) is undefined for the type DefaultMockMvcBuilder
#ContextConfiguration(locations = { "classpath:/testApplicationRestService.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
public class CustomerControllerTest {
#Rule
public final RestDocumentation restDocumentation = new RestDocumentation(
"build/generated-snippets");
#Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
#Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.build();
}
}
Spring REST Docs requires Spring Franework 4.1 or later. The apply method is new in Spring Framework 4.1. The compile failure means that you have an earlier version on the classpath. You should update your pom.xml or build.gradle to ensure that you're using the required version.

Resources