如何继承 StrutsSpringTestCase 并注入 Mock Service?

解读

在国内一线互联网或外包公司的 Java 岗面试中,**“Struts2 + Spring 集成测试”**是高频考点。面试官真正想确认的是:

  1. 你是否知道 StrutsSpringTestCase 已经帮你完成了 Struts2 容器 + Spring 容器 的双启动;
  2. 你是否能把 @Autowired 的 Service 层用 Mockito 无痛替换,从而把 Web 层单元测试从慢速的集成测试中剥离出来;
  3. 你是否熟悉 Spring 5.x + JUnit 4/5 在国内项目中的主流写法(Spring Boot 项目虽然多,但老系统仍用 Struts2)。

一句话:既要让 Struts2 的 Action 跑在测试容器里,又要让 Action 里调用的 Service 是“假”的,而且不能改生产代码。

知识点

  1. StrutsSpringTestCase 本质是对 StrutsTestCase 的扩展,在 setupBeforeInitDispatcher() 里会启动 Spring 容器,并把 Spring 的 ContextLoaderListener 初始化参数写死为 classpath*:applicationContext-test.xml。
  2. Spring 3.2+ 提供的 @Profile 与 @ActiveProfiles("test") 是国内最常用的 Mock 方案,比手动反射 set 进去更干净。
  3. Mockito 的 @Mock + @InjectMocks 只能给普通 POJO 用;在 Struts2 的 Action 里,Spring 负责注入,因此必须用 Spring 的 @Primary 或 @Profile 把 Mock Bean 覆盖掉真实现。
  4. 国内项目 90% 还在用 JUnit 4,所以必须重写 getContextLocations() 返回自定义测试配置,而不是用 @ContextConfiguration(那是 JUnit 5 的玩法)。
  5. OGNL 表达式 在测试模式下仍会执行,如果 Mock Service 返回空,可能触发 NullPointerException,需要 Mockito.when(...).thenReturn(new ArrayList<>()) 给足返回值。

答案

  1. 引入依赖(Maven 坐标,国内阿里镜像):
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-junit-plugin</artifactId>
    <version>2.5.30</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.21</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>4.6.1</version>
    <scope>test</scope>
</dependency>
  1. 在 src/test/resources 下新建 applicationContext-test.xml,只扫描测试专用配置:
<context:component-scan base-package="com.xxx.service"/>
<bean id="userService" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.xxx.service.UserService"/>
</bean>
  1. 编写测试类,关键点是覆盖 getContextLocations() 并显式指定测试配置文件:
public class UserActionTest extends StrutsSpringTestCase {

    @Override
    protected String getContextLocations() {
        return "classpath*:applicationContext-test.xml";
    }

    @Test
    public void testList() throws Exception {
        // 由于 Action 里调用的是 Mock,因此需要先打桩
        UserService userService = applicationContext.getBean(UserService.class);
        Mockito.when(userService.findAll()).thenReturn(Arrays.asList(new User(1L,"mock")));

        // 模拟 MVC 请求
        ActionProxy proxy = getActionProxy("/user/list");
        UserAction action = (UserAction) proxy.getAction();
        String result = proxy.execute();

        assertEquals("success", result);
        assertEquals(1, action.getUserList().size());
        assertEquals("mock", action.getUserList().get(0).getName());
    }
}
  1. 运行 mvn test,控制台出现 “Loaded action configuration from struts.xml” 且测试通过,即表示 Mock Service 注入成功。

拓展思考

  1. 如果项目已迁到 Spring Boot,但 Action 层仍保留 Struts2,可以用 @WebMvcTest + @AutoConfigureMockMvc 吗?
    答:不行。Struts2 的 Filter 不在 Spring MVC 链路上,必须继续用 StrutsSpringTestCase 或 @StrutsJUnit4TestCase(社区扩展)。

  2. 国内很多银行项目把 Struts2 配置文件拆成 struts-action.xml、struts-interceptor.xml 等多个文件,测试时如何一次性加载?
    答:重写 getConfigPath() 返回逗号分隔的字符串即可,例如:

@Override
protected String getConfigPath() {
    return "struts-default.xml,struts-plugin.xml,struts-action.xml";
}
  1. 当 Mock Service 里需要返回 PageInfo 这类 MyBatis 分页对象时,记得 Mockito.deepStub 或手动 new 一个完整对象**,否则 OGNL 在 JSP 里取 pageInfo.list 会再次触发空指针,导致测试 200 但页面 500,面试官会追问“为什么单元测试过了,联调却崩了”。

  2. 如果面试官追问“不用 Spring 测试容器,纯 Mockito 能不能注入?”
    答:可以,但必须在 setUp() 里用 ReflectionTestUtils.setField(action, "userService", mockService),并手动调用 action.setServletRequest(request) 等,代码量翻倍且容易漏掉 Struts2 的 ValueStack 初始化,国内项目不推荐。

掌握以上细节,你在面试中就能用 “Mock 覆盖 + 零侵入” 这一句话打动面试官,并顺势引出 “后续我们计划把 Struts2 迁到 Spring MVC” 的演进思路,直接拿到加分。