我尝试使用参数PersistentEntityResourceAssembler为Restcontroller实现JUnit-Test。
这是我的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);
}
}
我的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);
}
}
当启动junit-test时,我得到以下异常:
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
如果我删除参数PersistentEntityResourceAssembler,那么everthing工作正常。但是der RestController是由一个工具生成的,所以我不可能删除它。
答案 0 :(得分:0)
从你的控制器方法我不知道你是否使用PersistentEntityResourceAssembler。请检查您的使用案例。要解决此问题,可以在控制器中使用@RepositoryRestController而不是@RestController。请检查http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers。我发现一些不同的用例报告了类似的问题。此问题仍处于开放状态。 https://jira.spring.io/browse/DATAREST-657
答案 1 :(得分:-1)
似乎你错过了一些东西。 我遇到了这个错误并修复了它,问题是我忘了在方法的参数中添加注释@RequestBody。 下一个代码工作正常:
//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));