[英]Spring Security causing problems when doing unit tests on REST controller
So basically i am doing some unit tests on my rest controller, before using spring security everything was working smoothly, after adding it and setting the spring security to my mockmvc, it's always returning a 302 and nothing else, after tinkering with my code and the浏览器我发现登录后,我确实收到了一个 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: When testing my REST api which is protected by spring security, i am not able to reach the api from the tests.
对于 spring 安全集成测试,我们可以使用@WithMockUser
作为11. 测试方法安全(当前 spring-security 指南)提出的方法。
然而,测试“受限场景”也很好,我们将提供未经授权/忽略/匿名用户,并断言相应的反应(例外、http 代码、重定向......)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.