@AuthenticationPrincipal
と注釈されたパラメータとしてUserDetails
を受け取る残りのエンドポイントをテストする際に問題があります。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));
...
};
}
}
Testクラス:
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
スタンドアロンのセットアップと認証を組み合わせて使用する方法はありませんか? – andrucz
それはどこですか? – OrangeDog