Ho problemi a provare a testare un endpoint di riposo che riceve un UserDetails
come un parametro annotato con @AuthenticationPrincipal
.Inject @AuthenticationPrincipal quando l'unità esegue il test di un controller Spring REST
Sembra come l'istanza utente creato nello scenario di prova non viene utilizzato, ma un tentativo di creare un'istanza utilizzando costruttore di default è fatta invece: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.andrucz.app.AppUserDetails]: No default constructor found;
REST endpoint:
@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));
...
};
}
}
classe 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());
}
}
Come risolvere il problema senza passare a webAppContextSetup
? Vorrei scrivere test con il controllo totale dei servizi di simulazione, quindi sto usando standaloneSetup
.
È necessario [seguire queste istruzioni] (http://docs.spring.io/spring-security /site/docs/4.0.x/reference/htmlsingle/#test-mockmvc). – OrangeDog
Quindi non c'è modo di usare standaloneSetup combinato con l'autenticazione? – andrucz
Dove lo dice? – OrangeDog