测试使用PersistentEntityResourceAssembler的自定义RepositoryRestController
我有一个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.()
据推测,这里没有正确配置某些东西,因为我错过了整个数据层。 有没有办法嘲笑PersistentEntityResourceAssembler
? 或者我可以在这里使用另一种方法?
我现在结束了:
@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc
它的缩减是测试将启动完整的Spring应用程序上下文(但没有服务器)。
我最终在这里做了一个有点hacky的解决方案:
- 我从控制器方法中删除了
PersistentEntityResourceAssembler
。 - 我向控制器添加了一个
@Autowired RepositoryEntityLinks
,我在其上调用linkToSingleResource
来根据需要创建链接。 -
我在我的测试类中添加了一个
@MockBean RepositoryEntityLinks
,并配置了mocking以返回一些合理的东西:given(repositoryEntityLinks.linkToSingleResource(any(Identifiable.class))) .willAnswer(invocation -> { final Identifiable identifiable = (Identifiable) invocation.getArguments()[0]; return new Link("/data/entity/" + identifiable.getId().toString()); });
这远非理想 – 我很想知道是否有一种方法可以获得足够的数据层,我可以依赖PersistentEntityResourceAssembler
。