测试使用 PersistentEntityResourceAssembler 的自定义 RepositoryRestController [英] Testing a custom RepositoryRestController that uses a PersistentEntityResourceAssembler
问题描述
我有一个 RepositoryRestController
为一些持久实体公开资源.
I have a RepositoryRestController
that exposes resources for some persistent entities.
我的控制器上有一个方法,它需要一个 PersistentEntityResourceAssembler
来帮助我自动生成资源.
I have a method on my controller that takes a PersistentEntityResourceAssembler
to help me generate the resources automatically.
@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)));
}
}
(人为的例子,但它省去了我的用例的无关细节的太多细节)
(Contrived example, but it saves going into too much detail about irrelevant details of my use-case)
我想为我的控制器编写一个测试(我的真实用例实际上值得测试),并计划使用 @WebMvcTest.
I'd like to write a test for my controller (my real use-case is actually worth testing), and am planning on making use of @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
?或者我可以在这里使用的另一种方法?
Presumably something is not being configured correctly here because I'm missing the entire data layer. Is there some way of mocking out the PersistentEntityResourceAssembler
? Or another approach I could use here?
推荐答案
我现在结束了:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
它的缺点是测试将启动完整的 Spring 应用程序上下文(但没有服务器).
The downsite of it is that the test would start the full Spring application context (but without the server).
这篇关于测试使用 PersistentEntityResourceAssembler 的自定义 RepositoryRestController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!