2016-09-03 15 views
1

あなたは私を助けてくれますか?JUnit for RestControllerパラメータPersistentEntityResourceAssembler

パラメータ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のテストを開始するとき、私は次の例外を取得:私が削除した場合

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を継承すると、これまでどおりに動作します。しかし、der RestControllerはツールによって生成されるため、これを削除することはできません。

答えて

0

コントローラメソッドからは、PersistentEntityResourceAssemblerを使用しているかどうかわかりません。ユースケースを確認してください。これを修正するには、@ RestControllerの代わりに@RepositoryRestControllerを使用することができます。 http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlersにご確認ください。いくつかの異なるユースケースで同様の問題が報告されていることがわかりました。この問題はまだ開いた状態です。 https://jira.spring.io/browse/DATAREST-657

+0

ありがとうございました。ただし、動作しません。私はコントローラを変更しましたが、私はまだ同じエラーがあります。コントローラはツールによって生成されたので、PersistentEntityResourceAssemblerを削除することはできません。 –

+0

この変更後、どのようなエラーがありましたか?あなたはPostmanを使ってあなたのサービスを打つことを試みましたか? – abaghel

+0

エラーはorg.springframework.web.util.NestedServletExceptionです:要求の処理に失敗しました。 org.springframework.beans.BeanInstantiationException:インスタンス化に失敗しました。ネストされた例外はjava.lang.NoSuchMethodExceptionです:org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler。 。は()org.springframework.web.servlet.FrameworkServlet.doPostでorg.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979) \t(FrameworkServlet –

-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)); 
関連する問題