2017-10-10 70 views
2

我有一個RepositoryRestController公開某些持久實體的資源。測試使用PersistentEntityResourceAssembler的自定義RepositoryRestController

我在我的控制器上有一個方法,它需要一個PersistentEntityResourceAssembler來幫助我自動生成資源。

@RepositoryRestController 
@ExposesResourceFor(Customer.class) 
@RequestMapping("/api/customers") 
public class CustomerController { 

    @Autowired 
    private CustomerService service; 

    @RequestMapping(method = GET, value="current") 
    public ResponseEntity getCurrent(Principal principal Long id, PersistentEntityResourceAssembler assembler) { 
     return ResponseEntity.ok(assembler.toResource(service.getForPrincipal(principal))); 
    } 
} 

(人爲的例子,但它節省了進入我的用例不相關的細節太多細節)

我想編寫一個測試我的控制器(我真正的用例是實際上值得測試),並計劃使用@WebMvcTest。

所以我有以下的測試類:

@RunWith(SpringRunner.class) 
@WebMvcTest(CustomerController.class) 
@AutoConfigureMockMvc(secure=false) 
public class CustomerControllerTest { 
    @Autowired 
    private MockMvc client; 

    @MockBean 
    private CustomerService service; 

    @Test 
    public void testSomething() { 
     // test stuff in here 
    } 

    @Configuration 
    @Import(CustomerController.class) 
    static class Config { 
    } 

} 

但我得到一個異常說java.lang.NoSuchMethodException: org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.<init>()

大概的東西沒有被正確配置在這裏,因爲我失去了整個數據層。有沒有辦法嘲笑PersistentEntityResourceAssembler?或者我可以在這裏使用另一種方法?

+0

如果您讓「CustomerController」類公開,會發生什麼? –

+0

對不起,這是一個C&P錯誤,並沒有涉及到這個問題(雖然很好,但!)。這裏的問題是,春天看到它需要通過PERA,但沒有。問題幾乎可以肯定與我的測試配置。 – Martin

回答

2

我現在結束了與:

@RunWith(SpringRunner.class) 
@SpringBootTest 
@AutoConfigureMockMvc 

它的downsite是,測試將開始全面Spring應用程序上下文(但沒有服務器)。

0

我結束了在這裏做一個稍微哈克解決方案:

  • 我刪除了從控制器方法PersistentEntityResourceAssembler
  • 我向控制器添加了一個@Autowired RepositoryEntityLinks,我在其上呼叫linkToSingleResource根據需要創建鏈接。
  • 我添加了一個@MockBean RepositoryEntityLinks我的測試類,並配置了嘲諷返回的東西明智的:

    given(repositoryEntityLinks.linkToSingleResource(any(Identifiable.class))) 
         .willAnswer(invocation -> { 
          final Identifiable identifiable = (Identifiable) invocation.getArguments()[0]; 
          return new Link("/data/entity/" + identifiable.getId().toString()); 
         }); 
    

這是很不理想 - 我很想知道,如果有想起來的一種方式足夠的數據層,我可以依靠PersistentEntityResourceAssembler

相關問題