我们正在尝试向我们的 Spring 项目添加单元测试Controllers
(顺便说一句,集成测试工作正常),但是我们遇到了一个非常奇怪的行为,当我们添加配置时@EnableGlobalMethodSecurity
(使用 JSR-250 注释)如果控制器实现了一个接口(无论接口)Controller
,Spring 应用程序上下文都不包含“请求处理程序”(我在方法上检查了它org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(String beanName)
:),也就是说,在控制器(@PostMapping
,...)中定义的请求映射没有注册为潜在位置,但是如果接口被删除,然后控制器和路径找到没有问题。
这是我的控制器(简化版),界面简单MyInterface
:
@RestController
@RequestMapping(path = "/api/customer")
@RolesAllowed({Role.Const.ADMIN})
public class CustomerController implements MyInterface {
@Override // The only method in MyInterface
public void myMethod(Object param) throws QOException {
System.out.println("Hello");
}
@PostMapping(path = {"/", ""})
public Customer create(@RequestBody Customer data) throws QOException {
return customerService.create(data);
}
}
这是测试类(如果我删除@EnableGlobalMethodSecurity
配置类一切正常):
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = CustomerController.class)
@Import({ CustomerController.class, TestAuthConfiguration.class, TestAuthConfiguration2.class}) //, TestAuthConfiguration.class })
@ActiveProfiles({"test", "unittest"})
@WithMockUser(username = "test", authorities = { Role.Const.ADMIN })
class CustomerControllerTest {
private static final Logger LOG = LogManager.getLogger(CustomerControllerTest.class);
@EnableWebSecurity
protected static class TestAuthConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
LOG.info("configure(HttpSecurity http) ");
http.csrf().disable().authorizeRequests().filterSecurityInterceptorOncePerRequest(true)
.antMatchers("/api/session/**").permitAll() //
.antMatchers("/api/**").authenticated() //
.anyRequest().permitAll().and() //
.addFilterBefore(new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
LOG.info("User authenticated: {}, roles: {}", auth.getName(), auth.getAuthorities());
}
filterChain.doFilter(request, response);
}
}, BasicAuthenticationFilter.class).sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
@EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = false)
protected static class TestAuthConfiguration2 extends GlobalMethodSecurityConfiguration {
@Bean
public GrantedAuthorityDefaults grantedAuthorityDefaults() {
return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
}
}
@Autowired
MockMvc mockMvc;
@Test
void testCreate() throws Exception {
Customer bean = new Customer();
bean.setName("Test company");
when(customerServiceMock.create(bean)).thenReturn(bean);
mockMvc.perform(post("/api/customer")
.content(JsonUtils.toJSON(bean)).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Test company"));
}
}
我不明白发生了什么,我试图找到一个基于注释 JSR-250(@RollesAllowed)的具有安全性的控制器中的单元测试示例,但我没有发现任何有用的东西,无论如何这个问题听起来(到我)到一个错误,但我不确定,所以欢迎任何帮助。
库版本:
- Spring Boot 版本:2.2.2
- 弹簧核心:5.2.1
- 模拟核心:3.1.0