【发布时间】:2020-08-07 19:50:57
【问题描述】:
所以基本上我在我的 rest 控制器上做一些单元测试,在使用 spring security 之前一切工作顺利,在添加它并将 spring security 设置到我的 mockmvc 之后,它总是返回 302 而没有别的,在修补我的代码和浏览器我发现登录后,我确实收到了一个 302 代码,由于重定向,我确实收到了预期的 302 代码,似乎我的配置中的 loginProcessingUrl 导致了这个:
我的spring安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/showMyLoginPage")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/")
.logoutUrl("/logoutUser")
.and()
.csrf()
.disable();
}
我正在测试的 REST 方法:
@GetMapping(path = "/list/getProducts")
public String getProducts()
{
List<Product> products = productService.getProducts();
return gson.toJson(products);
}
最后是我的测试:
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "file:src/test/java/resources/ProductCRUD-servlet.xml")
@WebAppConfiguration
public class ProductControllerTest
{
@Autowired
WebApplicationContext context;
@InjectMocks
private ProductRestController productRestController;
@Mock
private ProductService productService;
private MockMvc mockMvc;
@Before
public void setup()
{
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
public void getAllProductsTest() throws Exception
{
List<Product> products = new ArrayList<>();
products.add(new Product("4532", 123, "Product test", "test"));
Mockito.when(productService.getProducts())
.thenReturn(products);
mockMvc.perform(MockMvcRequestBuilders
.get("/product/list/getProducts"))
.andExpect(status().isOk)
.andExpect(content().string(containsString("\"productId\":\"4534\"")));
}
所以发生的事情是,即使我的网站正在运行并且我正在检索我的 json,登录过程还是以某种方式弄乱了我的测试。
即使我将测试状态代码设置为 302 而不是 200,它也不会返回任何内容。
Expected :a string containing "\"productId\":\"4534\""
Actual :""
TLDR: 在测试受 Spring Security 保护的 REST api 时,我无法从测试中访问 api。
【问题讨论】:
-
如果你想(前端)集成测试控制器,我会去
@WithMockUser。如果您想测试安全配置,请断言 403/重定向(无模拟/禁止/匿名用户)。 -
@xerx593 正确,如果您想将此添加为答案。
-
欢迎并感谢您,对不起,它会很短! :)
标签: java spring spring-security