You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Spring 5中如何创建MockMvc与WebDriver?附测试用例示例

我来帮你梳理下Spring 5环境下MockMvc和WebDriver的创建方式,结合你给出的测试用例,咱们把代码补全并拆解说明:

Spring 5中MockMvc与WebDriver的测试用例实现

首先是完整的测试类代码,我帮你补全了未完成的部分:

@RunWith(SpringRunner.class)
@WebAppConfiguration("/src/main/resources")
@ContextConfiguration(classes = {MvcConfig.class})
public class ExampleTests {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;
    private WebDriver driver;

    @Before
    public void setup() {
        // 初始化MockMvc
        this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
        
        // 初始化MockMvcHtmlUnitDriver(WebDriver实现)
        this.driver = MockMvcHtmlUnitDriverBuilder.webAppContextSetup(this.context).build();
    }

    // 示例MockMvc测试方法
    @Test
    public void testMockMvcRequest() throws Exception {
        mvc.perform(get("/home"))
           .andExpect(status().isOk())
           .andExpect(view().name("home"));
    }

    // 示例WebDriver测试方法
    @Test
    public void testWebDriverNavigation() {
        driver.get("http://localhost:8080/home");
        Assert.assertEquals("Home Page", driver.getTitle());
    }
}

核心注解说明

咱们先看看类上的几个关键注解:

  • @RunWith(SpringRunner.class):让JUnit运行在Spring测试环境中,支持Spring的依赖注入、上下文加载等核心特性
  • @WebAppConfiguration("/src/main/resources"):声明这是一个Web应用测试类,指定Web资源的根目录(这里对应项目的resources目录)
  • @ContextConfiguration(classes = {MvcConfig.class}):加载指定的Spring配置类,用来初始化WebApplicationContext,复用项目中的MVC配置逻辑

MockMvc的创建

在setup()方法中,通过MockMvcBuilders.webAppContextSetup(this.context).build()创建MockMvc实例:

  • 这种方式基于已有的WebApplicationContext构建,能完全复用你项目中的Spring MVC配置(比如拦截器、视图解析器、消息转换器等)
  • MockMvc主要用于无容器的MVC层测试,可以直接模拟HTTP请求,验证响应状态码、视图名称、模型数据等,不需要启动完整的Web服务器,测试效率很高

WebDriver(MockMvcHtmlUnitDriver)的创建

通过MockMvcHtmlUnitDriverBuilder.webAppContextSetup(this.context).build()创建WebDriver实例:

  • 这是Spring Test提供的特殊WebDriver实现,结合了MockMvc的上下文优势和HtmlUnit的浏览器模拟能力
  • 它不需要启动真实的Web服务器,而是直接通过MockMvc处理请求,同时能模拟浏览器的DOM操作、页面导航、表单提交等行为,适合轻量级的端到端测试
  • 如果你需要更真实的浏览器模拟,也可以替换成ChromeDriver、FirefoxDriver等,但需要额外配置对应浏览器的驱动程序

必要依赖提示

要运行这些测试,你需要在项目中引入以下依赖(以Maven为例):

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.24</version> <!-- 替换为你使用的Spring 5具体版本 -->
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>htmlunit-driver</artifactId>
    <version>2.67.0</version> <!-- 适配Spring 5的稳定版本 -->
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

内容的提问来源于stack exchange,提问作者JuarX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:25:28