【发布时间】:2020-05-23 11:55:45
【问题描述】:
我无法为我的 REST 控制器集成测试设置身份验证。 Controller的方法是这样的:
@RestController
@RequestMapping(BASE_URL)
@RequiredArgsConstructor
public class EventController {
public static final String BASE_URL = "/api/event";
@PostMapping
@PreAuthorize("hasRole('USER')")
public void createEvent() {
System.out.println("I am in controller");
}
}
这是我的测试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class EventControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
void create() throws Exception {
this.mockMvc.perform(post(EventController.BASE_URL)
.with(authentication(new UsernamePasswordAuthenticationToken(
new MyPrincipal(100, "denis"),
null,
Collections.singletonList(new SimpleGrantedAuthority("USER"))
)))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
由于401 状态,我的测试总是失败,所以我的模拟身份验证不起作用。你能告诉我如何解决吗?谢谢你的建议。
【问题讨论】:
-
身份验证如何在您的应用程序中工作?
-
@SupunWijerathne 有基于 jwt 令牌的身份验证。
标签: spring-boot spring-security spring-test spring-oauth2 spring-mvc-test