如何批量实现WildFly 36上Arquillian测试的Elytron身份认证调用?
批量为WildFly 36上的Arquillian测试添加Elytron认证调用的方案
针对你需要给数千个Arquillian测试批量添加Elytron认证上下文的需求,不需要自定义Arquillian Runner,推荐以下两种更简洁的实现方式:
1. 通用基类封装认证逻辑
创建一个抽象基类,将认证和runAs逻辑封装为通用方法,所有测试类继承该基类即可复用逻辑:
public abstract class AuthenticatedBaseTest { private SecurityIdentity securityIdentity; @Before public void initAuthentication() { // 替换为你的实际认证参数(用户名、密码、安全领域等) securityIdentity = SecurityDomain.getCurrent().authenticate("testUser", "testPassword".toCharArray()); } protected void executeAsAuthenticated(Runnable businessAction) { securityIdentity.runAs(businessAction); } }
后续所有测试类继承这个基类,将原来直接调用EJB的代码:
simpleService.sayHello();
替换为调用封装方法:
executeAsAuthenticated(() -> simpleService.sayHello());
如果测试数量庞大,可借助IDE的全局替换功能批量完成代码修改,效率更高。
2. CDI拦截器自动包裹认证上下文
通过CDI拦截器实现测试方法的自动拦截,无需修改测试方法代码,只需添加注解即可:
步骤1:定义拦截器绑定与拦截器实现
// 拦截器绑定注解 @InterceptorBinding @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface RunAsAuthenticated { } // 拦截器逻辑实现 @Interceptor @RunAsAuthenticated public class AuthenticationInterceptor { @AroundInvoke public Object wrapWithAuthentication(InvocationContext ctx) throws Exception { SecurityIdentity securityIdentity = SecurityDomain.getCurrent().authenticate("testUser", "testPassword".toCharArray()); return securityIdentity.runAs(() -> { try { return ctx.proceed(); } catch (Exception e) { throw new RuntimeException("测试执行失败", e); } }); } }
步骤2:启用拦截器
在项目的beans.xml中注册该拦截器:
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd" version="2.0" bean-discovery-mode="all"> <interceptors> <class>com.yourpackage.AuthenticationInterceptor</class> </interceptors> </beans>
步骤3:标记测试类/方法
在需要认证的测试类或方法上添加@RunAsAuthenticated注解,测试方法执行时会自动被包裹在认证上下文里:
@RunWith(Arquillian.class) @RunAsAuthenticated public class SimpleServiceTest { @EJB private SimpleService simpleService; @Test public void testSayHello() { // 无需修改原有代码,自动在认证上下文执行 simpleService.sayHello(); } }
总结
- 若允许少量代码替换,优先选择通用基类+全局替换的方式,实现简单且无额外配置成本;
- 若希望完全不修改原有测试代码,推荐CDI拦截器方案,通过注解实现批量生效;
- 自定义Arquillian Runner复杂度高,需处理Arquillian内部执行逻辑,不推荐使用。
内容的提问来源于stack exchange,提问作者dkalna
相关产品推荐
相关产品推荐

