我在嘗試測試接收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