could you please help me.
I try to implement an JUnit-Test for a Restcontroller with parameter PersistentEntityResourceAssembler.
Here is my RestController:
import java.util.Map;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController2 {
#Autowired
ProducerTemplate pt;
#RequestMapping(value = "/greeting2", method = RequestMethod.POST)
public ResponseEntity<Greeting> updateGreeting( PersistentEntityResourceAssembler assembler,
#RequestHeader HttpHeaders header, #RequestBody Greeting greeting) {
Map<String, Object> headers = (Map) header.toSingleValueMap();
greeting=(Greeting) pt.requestBodyAndHeaders("direct:start", greeting, headers);
return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
}
}
And my JunitTest:
public class GreetingControllerMocksTest2 extends AbstractControllerTest2 {
#Mock
private ProducerTemplate producerTemplate;
#InjectMocks
private GreetingController2 greetingController2;
#Before
public void setUp() {
// Initialize Mockito annotated components
MockitoAnnotations.initMocks(this);
// Prepare the Spring MVC Mock components for standalone testing
setUp(greetingController2);
}
#Test
public void testRestEndpoint() throws Exception {
// Create some test data
Greeting entity = new Greeting(5,"Rudi");
// Stub the GreetingService.update method return value
when(producerTemplate.requestBodyAndHeaders(anyString(),anyObject(),
anyObject())).thenReturn(entity);
// Perform the behavior being tested
String uri = "/greeting2";
String inputJson = super.mapToJson(entity);
MvcResult result = mvc
.perform(MockMvcRequestBuilders.post(uri)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content(inputJson))
.andReturn();
// Extract the response status and body
String content = result.getResponse().getContentAsString();
int status = result.getResponse().getStatus();
// Verify the GreetingService.update method was invoked once
verify(producerTemplate,
times(1)).requestBodyAndHeaders(anyString(),anyObject(),anyObject());
// Perform standard JUnit assertions on the test results
Assert.assertEquals("failure - expected HTTP status 200", 200, status);
Assert.assertTrue(
"failure - expected HTTP response body to have a value",
content.trim().length() > 0);
Greeting updatedEntity = super.mapFromJson(content, Greeting.class);
Assert.assertNotNull("failure - expected entity not null",
updatedEntity);
}
}
When starting the junit-test i get the following Exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.<init>()
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at org.example.ws.web.api.GreetingControllerMocksTest2.testRestEndpoint(GreetingControllerMocksTest2.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.<init>()
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:107)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:80)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:106)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:99)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
... 39 more
Caused by: java.lang.NoSuchMethodException: org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:104)
... 52 more
If i remove the paramter PersistentEntityResourceAssembler, then everthing works fine. But der RestController is generated by a tool, so it is not possible for me to remove this.
From your controller method I don't see if you are using PersistentEntityResourceAssembler. Please check your use case. To fix this, in your controller, you can use #RepositoryRestController instead of #RestController. Please check http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers. I found the similar issue has been reported for some different use case. This issue is still in open state. https://jira.spring.io/browse/DATAREST-657
It seems that you have missed something.
I faced this error and fixed it, the problem was that I forgot to add an annotation #RequestBody to the parameter of the method.
Next code works fine:
//interface:
#ResponseStatus(value = HttpStatus.ACCEPTED)
#RequestMapping(method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE })
public Message greeting(#RequestBody GreetingRequestMessage requestMessage);
//implementation:
public Message greeting(#RequestBody GreetingRequestMessage requestMessage) {
}
//setup #Before:
mvc = MockMvcBuilders.standaloneSetup(testObj).build();
GreetingRequestMessage requestMessage = new GreetingRequestMessage();
payloadString = mapper.writeValueAsString(requestMessage);
//test:
payloadString = mapper.writeValueAsString(request);
mvc.perform(
MockMvcRequestBuilders.post("/greeting")
.content(payloadString)
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().is(202));
Related
So i have searched all related questions here and found no answer that worked on mine. With that being said I am trying to unit test my spring-boot application with Mockito.
Here is my controller and the function i am trying to test.
#RestController
public class UserController {
#Autowired
UserRepository userRepository;
#GetMapping("/user")
public List<User> getAllUsers() {
return userRepository.findAll();
}
#GetMapping("/user/{id}")
public User getUser(#PathVariable Integer id) {
return userRepository.findById(id).get();
}
I am trying to test getUser function
here is my Test Controller
#RunWith(SpringJUnit4ClassRunner.class)
public class UserControllerTest {
private MockMvc mockMvc;
#MockBean
private UserController userController;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
#Test
public void getUserTest() throws Exception{
mockMvc.perform(get("/user/100").contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("application/json"))
.andExpect(jsonPath("$.role").value("deliverer"));
}
So firstly when I run this i get following error
java.lang.AssertionError: Content type not set
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:37)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:70)
at org.springframework.test.util.AssertionErrors.assertNotNull(AssertionErrors.java:106)
at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$contentTypeCompatibleWith$1(ContentResultMatchers.java:103)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at eldercare.RESTapi.controller.UserControllerTest.getUserTest(UserControllerTest.java:57)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
with following data being printed
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
I have tested putting #ResponseBody in my Controller does not make any difference. I have also tested as stated in other post #RequestMapping(value="/user/{id}", method= RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) that doesn't work either still get the same error.
If I dont have this check .andExpect(content().contentTypeCompatibleWith("application/json")) then i get the error stating java.lang.AssertionError: No value at JSON path "$.role"
I think you should be mocking the UserRepository and not the UserController.
I'm trying to test my simple rest controller method to get all offers but i always get java.lang.AssertionError: Status Expected :200 Actual :404. I don't know if there is problem with mocking or finding my component. I was trying to find solution in other posts but none of them was matching to my problem. Any ideas?
My Service:
#Service
#Transactional
class OfferServiceImpl implements OfferService {
private OfferRepository offerRepository;
#Autowired
public OfferServiceImpl(OfferRepository offerRepository) {
this.offerRepository = offerRepository;
}
#Override
public List<Offer> getAll(){
return (List<Offer>) offerRepository.findAll();
}
My Controller:
#RestController
#RequestMapping("/api/offers")
class OfferRestController {
private OfferService offerService;
#Autowired
public OfferRestController(OfferService offerService) {
this.offerService = offerService;
}
#GetMapping
List<Offer> getAllOffers(){
return offerService.getAll();
}
My Test Class:
#RunWith(SpringRunner.class)
#WebMvcTest(value = OfferRestController.class)
public class OfferControllerIntegrationTest {
private Offer offer1;
private Offer offer2;
#MockBean
private OfferService offerServiceMock;
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private MockMvc mvc;
#Before
public void setUpOffers(){
offer1 = new Offer("Java Dev",
4000,
5000,
"CEO",
"Java",
"Lorem ipsum",
"user#gmail.com",
true);
offer2 = new Offer("PHP Dev",
4000,
5000,
"CEO",
"PHP",
"Lorem ipsum",
"user#gmail.com",
true);
}
#Before
public void setUp() {
this.mvc = standaloneSetup(new OfferRestController(offerServiceMock))
.alwaysExpect(MockMvcResultMatchers.content()
.contentType("application/json;charset=UTF-8"))
.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON))
.alwaysExpect(status().isOk())
.build();
this.mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.alwaysDo(print())
.build();
}
#Test
public void givenOffers_whenGetOffers_thenReturnJsonArray() throws Exception{
List<Offer> allOffers= Arrays.asList(offer1,offer2);
given(offerServiceMock.getAll()).willReturn(allOffers);
mvc.perform(get("/api/offers")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$",hasSize(2)))
.andExpect(jsonPath("$[0].name").value(offer1.getName()))
.andExpect(jsonPath("$[1].name").value(offer2.getName()))
.andDo(print());
verify(offerServiceMock,times(1)).getAll();
verifyNoMoreInteractions(offerServiceMock);
}
}
My App:
#SpringBootApplication
#EntityScan(basePackageClasses = {App.class, Jsr310JpaConverters.class})
#ComponentScan({"com"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
And my problem:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/offers
Parameters = {}
Headers = {Content-Type=[application/json]}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type =
org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at brozek.com.offer.OfferControllerIntegrationTest.givenOffers_whenGetOffers_thenReturnJsonArray(OfferControllerIntegrationTest.java:89)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Usually integration test setup should mock the controller created in the test Spring context with #WebMvcTest(value = OfferRestController.class). The usual syntax is:
#RunWith(SpringRunner.class)
#WebMvcTest(value = OfferRestController.class)
#AutoConfigureMockMvc
public class OfferRestControllerTest {
#MockBean
private OfferService offerService;
#Autowired
private MockMvc mvc;
}
In your test it's pointless to set Content-Type on GET request which has no body, remove
.contentType(MediaType.APPLICATION_JSON)
Starting from Spring 4.1 it's not necessary to use #Autowired on single constructor. You can simplify your code by removing #Autowired here:
public OfferServiceImpl(OfferRepository offerRepository) {
this.offerRepository = offerRepository;
}
I have created an rest api and tested via postman and able to get success response as expected. Now i have created Junit test case for the above api but while executing getting "java.lang.AssertionError: Status expected:<200> but was:<415> ". Not able to figure out why this exception is happening.
I'm new to both Mockito and MockMVC so any help would be appreciated.
Below is my test class
package com.example.demo.hystricks;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.Serializable;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.example.demo.DemoController;
import com.example.demo.DemoService;
import com.example.demo.InputModel;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes = DemoController.class)
public class DemoControllerTest {
private MockMvc mockMvc;
#InjectMocks
private DemoController demoController;
#MockBean
private DemoService demoService;
#MockBean
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
DemoController demoController = new DemoController(demoService);
this.mockMvc = MockMvcBuilders
.standaloneSetup(demoController).
setMessageConverters(mappingJackson2HttpMessageConverter).build();
}
#Test
public void postData() throws Exception {
InputModel inputModel = new InputModel("12345","Test","CSC",getEventTime());
System.out.println("before api....");
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/demoService")
.accept(MediaType.APPLICATION_JSON)
.content(inputModel.toString())
.contentType(MediaType.APPLICATION_JSON);
mockMvc.perform(requestBuilder)
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
System.out.println("after api....");
}
private LocalDateTime getEventTime() {
Instant instant = Instant.ofEpochMilli(Instant.now().toEpochMilli());
LocalDateTime eventTimestamp = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
return eventTimestamp;
}
}
My Rest Controller
#RestController
public class DemoController {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);
public final DemoService demoService;
public DemoController(DemoService demoService) {
this.demoService = demoService;
}
#RequestMapping(value = "demoService",method = RequestMethod.POST)
public ResponseEntity<String> postData(
#RequestBody InputModel inputModel){
LOGGER.info("DemoService Entered successfully");
demoService.postData(inputModel.getId(),inputModel.getName(),
inputModel.getDepartment(), inputModel.getJoinDate());
LOGGER.info("DemoService Exited successfully");
return new ResponseEntity<String>("success",HttpStatus.OK) ;
}
}
Console Message before api:
>2018-10-16 12:15:49.391 WARN 6200 --- [ main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported]
2018-10-16 12:15:49.437 INFO 6200 --- [ Thread-3] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#5023bb8b: startup date [Tue Oct 16 12:15:48 IST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#76a4ebf2
Failure Stack Trace:
>java.lang.AssertionError: Status expected:<200> but was:<415>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at com.example.demo.hystricks.DemoControllerTest.postData(DemoControllerTest.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
The issue is on this line:
#MockBean
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
You are mocking this converter. Create a instance using new instead:
this.mockMvc = MockMvcBuilders
.standaloneSetup(controller).
setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
Or as rightly mentioned by M. Dienum, you can do away with the below 2 lines from setUp() method and it'll work:
DemoController demoController = new DemoController(demoService);
this.mockMvc = MockMvcBuilders
.standaloneSetup(demoController).
setMessageConverters(mappingJackson2HttpMessageConverter).build();
After doing all this if you run into 400 error then your toString() method isn't producing valid json.
I am trying to write a test case for following controller code using JUnit.
But I am getting 500 code with null pointer Exception. (When I test this on Postman, it works without any exception.) I think HttpServeleRequest Request of validEmp might cause this null pointer exception to testGetMethod. Can any one please tell what I am doing wrong here and how to fix this? Thank you for your help:D
LoginService
public ReturnParam validEmp(HttpServletRequest request, String locale, String empKey, String accessToken) throws Exception {
ReturnParam rp = new ReturnParam();
rp.setFail("not available");
return rp;
}
LoginController
#RequestMapping(value = "/valid", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
public #ResponseBody ReturnParam validEmp(HttpServletRequest request,
#RequestParam(value = "locale", required = true) String locale,
#RequestParam(value = "empKey", required = true) String empKey,
#RequestParam(value = "accessToken", required = true) String accessToken) throws Exception {
return service.validEmp(request, locale, empKey, accessToken);
}
LoginControllerTest
public MockMvc mockMvc;
private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
public void testGetMethod(String url, String locale, String empKey, String acessToken) throws Exception {
mockMvc.perform(get(url).param("locale", locale).param("empKey",empKey).param("accessToken", acessToken))
.andDo(print())
.andExpect(status().isOk());
}
Console
java.lang.NullPointerException
at com.isu.ifm.hr.control.LoginController.validEmp(LoginController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144)
at com.isu.ifm.HttpMethodUnitTest.testGetMethod(HttpMethodUnitTest.java:21)
at com.isu.ifm.testcase.LoginControllerTest.TestCaseMain(LoginControllerTest.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
MockHttpServletRequest:
HTTP Method = GET
Request URI = /certificate/valid
Parameters = {locale=[ko_KR], empKey=[ISU_ST#18017], accessToken=[]}
Headers = {}
Handler:
Type = com.isu.ifm.hr.control.LoginController
Method = public com.pb.common.vo.ReturnParam com.isu.ifm.hr.control.LoginController.validEmp(javax.servlet.http.HttpServletRequest,java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception
Async:
Async started = false
Async result = null
Resolved Exception:
Type = java.lang.NullPointerException
ModelAndView:
View name = jsonView
View = null
Attribute = status
value = FAIL
Attribute = message
value = null
FlashMap:
MockHttpServletResponse:
Status = 500
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = jsonView
Redirected URL = null
Cookies = []
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext#5abca1e0: startup date [Thu Nov 01 16:46:45 KST 2018]; root of context hierarchy
INFO : org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Shutting down ExecutorService 'taskExecutor'
You need to mock your LoginService in LoginController. Try to add such code to LoginControllerTest.
#Mock
private LoginService loginService;
#InjectMocks
private LoginController loginController;
#Before
public void init(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(loginController)
.build();
}
I think problem ist not a request , but injection. According your stacktrace I would say, that service is null (injection in controller isn't working)
I am getting an exception when I try to run the Spring Web Service JUnit Test Using the Spring WebService ServerSide Integration Test using MockWebServiceClient. When I run the WebService Junit Test, I'm getting an exception:
No endpoint can be found for request [SaajSoapMessagehttp://schemas.xmlsoap.org/soap/envelope/}Envelope]
Spring_WS_ServletConfig
#Configuration
#EnableWs
#EnableTransactionManagement
// #ComponentScan({ "com.springws.endpoint", "com.mybatis.", "com.mapstruct" })
// #ImportResource({ "classpath:/SpringConfig/spring-database-config.xml" })
public class Spring_WS_ServletConfig extends WsConfigurerAdapter {
#Bean("StudentServiceWsdl")
public DefaultWsdl11Definition orders() throws SQLException {
DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
definition.setPortTypeName("StudentService_SpringWS_PortType");
definition.setLocationUri("http://localhost:8080/MvnSpringMcc/StudentService_SpringWS/");
definition.setTargetNamespace("com.springws.student/LearnSpringWs");
definition.setServiceName("SpringWSService");
// definition.setWsdl(new
// ClassPathResource("/wsdl/StudentService.wsdl"));
definition.setSchema(studentsSchema());
return definition;
}
#Bean
public XsdSchema studentsSchema() {
Resource resource = new ClassPathResource("/wsdl/StudentTask.xsd");
return new SimpleXsdSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validator = new PayloadValidatingInterceptor();
validator.setValidateRequest(true);
validator.setValidateResponse(true);
validator.setSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
}
}
TestConfig
#Configuration
#ComponentScan({ "com.springws.test", "com.mybatis.mapper.vo", "com.mybatis.service", "com.mapstruct.mapper",
"com.springws.endpoint", "com.mybatis.mapper" })
//#Import(Spring_WS_ServletConfig.class)
#ImportResource({ "classpath:testResources/spring-ws-test-database-config.xml" })
public class TestConfig {
}
CourseServiceEndPointServerSideIntegrationTest
#EnableTransactionManagement
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { TestConfig.class, Spring_WS_ServletConfig.class })
public class CourseServiceEndPointServerSideIntegrationTest {
#Autowired
ResourceLoader resourceLoader;
#Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
#Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);
}
#Test
public void courseEndpoint() throws Exception {
Resource requestPayLoad = resourceLoader.getResource("classpath:xmlTestFiles/RequestPayLoad.xml");
Resource responsePayLoad = resourceLoader.getResource("classpath:xmlTestFiles/ResponsePayLoad.xml");
mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
}
}
RequestPayLoad.xml File
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:lear="com.springws.student/LearnSpringWs" xmlns:stud="com.springws.student/StudentSchema">
<soapenv:Header />
<soapenv:Body>
<lear:GetCourseRequest>
<lear:Course>
<stud:courseID>100</stud:courseID>
</lear:Course>
</lear:GetCourseRequest>
</soapenv:Body>
</soapenv:Envelope>
Exception
CourseServiceEndpoint(com.springws.endpoint.CourseServiceEndpoint) Time elapsed: 0.219 sec <<< FAILURE!
java.lang.AssertionError: No endpoint can be found for request [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]
at org.springframework.ws.test.support.AssertionErrors.fail(AssertionErrors.java:39)
at org.springframework.ws.test.server.MockWebServiceClient.sendRequest(MockWebServiceClient.java:184)
at com.springws.serverside.test.CourseServiceEndPointServerSideIntegrationTest.courseEndpoint(CourseServiceEndPointServerSideIntegrationTest.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Results :
Failed tests: CourseServiceEndpoint(com.springws.serverside.test.CourseServiceEndPointServerSideIntegrationTest): No endpoint can be found for request [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]
The better way to solve this problem is to change for proper methods in RequestCreators
and ResponseMatchers for SOAP one.
import static org.springframework.ws.test.server.RequestCreators.withSoapEnvelope;
import static org.springframework.ws.test.server.ResponseMatchers.soapEnvelope;
Changes need to be done in our test method.
Before:
mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
After:
mockClient.sendRequest(withSoapEnvelope(requestPayLoad)).andExpect(soapEnvelope(responsePayLoad));
Finally I was able to solve the problem: Just provide the Soap Payload Information in the MockWebServiceClient.sendRequest's withPayload() & andExpect(payload()) methods.
RequestPayLoad.xml
<lear:GetCourseRequest xmlns:lear="com.springws.student/LearnSpringWs"
xmlns:stud="com.springws.student/StudentSchema">
<lear:Course>
<stud:courseID>100</stud:courseID>
</lear:Course>
</lear:GetCourseRequest>
ResponsePayLoad.xml
<ns3:GetCourseResponse xmlns:ns2="com.springws.student/StudentSchema"
xmlns:ns3="com.springws.student/LearnSpringWs">
<ns3:Course>
<ns2:courseID>100</ns2:courseID>
<ns2:courseName>Physics</ns2:courseName>
<ns2:courseCategory>Physics</ns2:courseCategory>
<ns2:credit>3.0</ns2:credit>
</ns3:Course>
</ns3:GetCourseResponse>