我在尝试测试接收UserDetails
作为参数@AuthenticationPrincipal
注解的其余端点时遇到问题。单元测试Spring REST控制器时注入@AuthenticationPrincipal
好像在测试场景中创建的用户实例不被使用,但使用默认构造函数实例化一个尝试,而不是: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
。
您需要[请按照这些说明](http://docs.spring.io/spring-security /site/docs/4.0.x/reference/htmlsingle/#test-mockmvc)。 – OrangeDog
因此,没有办法使用standaloneSetup与身份验证相结合? – andrucz
它在哪里说的? – OrangeDog