【发布时间】:2016-11-14 19:07:33
【问题描述】:
我在尝试测试接收 UserDetails 作为带有 @AuthenticationPrincipal. 注释的参数的 REST 端点时遇到问题
似乎没有使用在测试场景中创建的用户实例,而是尝试使用默认构造函数进行实例化:org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.andrucz.app.AppUserDetails]: No default constructor found;
REST 端点:
@RestController
@RequestMapping("/api/items")
class ItemEndpoint {
@Autowired
private ItemService itemService;
@RequestMapping(path = "/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Callable<ItemDto> getItemById(@PathVariable("id") String id, @AuthenticationPrincipal AppUserDetails userDetails) {
return () -> {
Item item = itemService.getItemById(id).orElseThrow(() -> new ResourceNotFoundException(id));
...
};
}
}
测试类:
public class ItemEndpointTests {
@InjectMocks
private ItemEndpoint itemEndpoint;
@Mock
private ItemService itemService;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(itemEndpoint)
.build();
}
@Test
public void findItem() throws Exception {
when(itemService.getItemById("1")).thenReturn(Optional.of(new Item()));
mockMvc.perform(get("/api/items/1").with(user(new AppUserDetails(new User()))))
.andExpect(status().isOk());
}
}
如何在不切换到webAppContextSetup 的情况下解决该问题?我想编写完全控制服务模拟的测试,所以我使用standaloneSetup.
【问题讨论】:
-
那么没有办法使用standaloneSetup结合认证?
-
它在哪里说的?
-
我不确定,但是我怎么能得到一个FilterChainProxy,这是必需的?
-
您也可以使用 webAppContextSetup,同时仍然通过
@ContextConfiguration保持对 bean 的完全控制。
标签: java spring spring-mvc spring-security spring-test