[英]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.