SpringMVC+MockMvc+dbUnit+cobertura构建测试框架(上)

简介: 本文基于SpringMVC搭建测试框架

通常情况我们可以借助easyMock及powerMock进行单元测试,但有时我们希望进行集成测试,可以通过发送http请求,测试某功能的完整性。


一般情况我们可以通过MockMvc模拟post或get请求,完成测试。但是当碰到delete或update进行测试时,容易对数据库造成污染,这时我们可以借助dbunit,对数据库进行测试数据的准备,测试完成后对事务进行回滚,方便下次测试。


1. maven集成测试组件


<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<!--数据库单元测试:消除单元测试对数据库的污染 start-->
<dependency>
    <groupId>com.github.springtestdbunit</groupId>
    <artifactId>spring-test-dbunit</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.dbunit</groupId>
    <artifactId>dbunit</artifactId>
    <version>2.4.9</version>
    <scope>test</scope>
</dependency>
<!--数据库单元测试:消除单元测试对数据库的污染 end-->


2. 定义测试基类,包括SpringMVC框架的集成,junit集成


@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@PropertySource("classpath:common.properties")
@TestPropertySource("classpath:common.properties")
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class,
        ServletTestExecutionListener.class,
        DbUnitTestExecutionListener.class}) //@1
@ContextConfiguration(
        {"classpath*:/spring-context.xml", "classpath*:/spring-mvc.xml", "classpath*:/spring-mybatis.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)//@2
@Transactional 
public abstract class BaseSpringJUnitTest {
    public static Logger logger = LoggerFactory.getLogger(BaseSpringJUnitTest.class);
    @Autowired
    private UserInfoService userInfoService;
    private static boolean inited = false;
    /**
     * junit模拟用户名
     */
    private final static String USER_NAME = "admin";
    /**
     * junit模拟验证码
     */
    private final static String VALIDATE_CODE = "1234";
    /**
     * junit模拟密码
     */
    private final static String PASSWORD = "Admin123456";
    public static String token = "";
    protected MockMvc mockMvc; //@3
    @Before //@4
    public void setUp() throws Exception {
        if (!inited) {
            String code = userInfoService.getValidateKey().get("validateKey").toString();
            RedisUtils.set("validCode:" + code, VALIDATE_CODE);
            UserInfoRequestParams params = new UserInfoRequestParams();
            params.setLoginName(USER_NAME);
            params.setPassword(MD5Util.encoderHexByMd5(PASSWORD));
            params.setValidateKey(code);
            params.setValidateCode(VALIDATE_CODE);
            JSONOutputObject result = userInfoService.webLogin(params);
            token = result.get("token").toString();
            TestCase.assertEquals(RsmsConstant.RESULT_SUCCESS_CODE, result.get(RsmsConstant.RESULT_CODE));
            inited = true;
        }
    }
}


@1:ServletTestExecutionListener 用于设置spring web框架启动时的RequestContextHolder本地线程变量。我们的项目比较特殊,在service层中是通过RequestContextHolder获取httpRequest对象(并非通过controller透传),如果不设置,则在service中或者切面中无法获取到request对象


@2:添加事务回滚,避免对数据库的污染


@3:定义MockMvc对象,模拟客户端的http请求


@4:初始化登录信息,根据自身需要设置,有些集成测试场景可能需要登录信息


3.编写测试类


public class UserInfoControllerTest extends BaseSpringJUnitTest {
    @Test
    @DatabaseSetup(type = DatabaseOperation.INSERT, value = {"/data/user-info.xml"})//@1
    public void testDeleteUsers() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
        //@2
        String responseString = mockMvc.perform(post("/user/deleteUsers")
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                .content("{\"idList\":10007}")
                .header("Current-Menu-Id", "102100")
                .header("Menu-Id", "102100")
                .accept(MediaType.ALL_VALUE)
                .header("token", token)
                .header("User-Agent", "Windows NT")
        ).andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
        JSONObject jsonObject = JSONObject.parseObject(responseString);
        Assert.assertEquals(jsonObject.get("resultCode"), "0000");
    }
}


@1:准备测试数据,因为在测试时,如果不自己准备数据,依赖数据库数据,那么数据库数据有可能被其他人误删或者数据库做了迁移或更新之后,我们的测试用例将无法跑通。


@2:通过mockMvc发送http请求,并解析请求结果,判断测试结果的正确性


4.准备测试数据(resource/data/user_info.xml)


<?xml version="1.0" encoding="UTF-8" ?>
<dataset>
    <t_user_info id="10007" login_name="admin_junit" password="" salt="" user_name="admin_junit" user_name_spell=""
              user_name_initial="" eid="" cellphone="" company_id="200" org_id="200" position=""/>
    <t_user_role id="1000" user_id="10007" role_id="1" />
</dataset>


5.jenkins集成,并统计单元测试覆盖率


<!-- 统计junit覆盖率 -->
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.1</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>report</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>


jenkins添加普通的maven构建任务,设置好git地址


插件管理中安装jacoco插件


build项设置如下


Root POM           pom.xml


Goals and options  test -Dmaven.repo.local=/opt/repository


构建后操作添加:Record JaCoCo coverage report


统计结果效果如下


image.png

单元测试覆盖率统计


6.配置邮件发送


邮件发送本人是集成了cobertura(和jacoco共一样,都是用于覆盖率的统计)


pom集成

<!-- cobertura统计junit覆盖率 -->
          <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <formats>
                        <format>html</format>
                        <format>xml</format>
                    </formats>
                </configuration>
            </plugin>


jenkins全局配置:jenkins->系统管理->系统设置


系统管理员地址:*********@qq.com


Extended E-mail Notification中配置如下


SMTP:smtp.qq.com


后缀@qq.com


点开高级


使用SMTP认证


用户名:*********@qq.com


密码:qq给的授权码(非邮箱的登录密码,授权码的获取:登录QQ邮箱:设置-SMTP设置-开启,需要发送短信,发送短信后,页面会显示授权码)


jenkins构建任务配置邮件发送


构建后操作:增加Editable Email Notification,点开高级,一定要设置triggers,否则无法触发


相关文章
|
2月前
|
Web App开发 人工智能 JavaScript
主流自动化测试框架的技术解析与实战指南
本内容深入解析主流测试框架Playwright、Selenium与Cypress的核心架构与适用场景,对比其在SPA测试、CI/CD、跨浏览器兼容性等方面的表现。同时探讨Playwright在AI增强测试、录制回放、企业部署等领域的实战优势,以及Selenium在老旧系统和IE兼容性中的坚守场景。结合六大典型场景,提供技术选型决策指南,并展望AI赋能下的未来测试体系。
|
13天前
|
安全 Linux 网络安全
Metasploit Framework 6.4.88 (macOS, Linux, Windows) - 开源渗透测试框架
Metasploit Framework 6.4.88 (macOS, Linux, Windows) - 开源渗透测试框架
223 0
|
5月前
|
边缘计算 安全 5G
高精度时钟同步测试仪:构建全场景时间同步生态
在数字化转型中,时间同步至关重要。西安同步电子科技的 SYN5106 高精度时钟测试仪,具备±20ns 时差测量精度与 GPS/北斗双模授时能力,广泛应用于电力、通信、金融和科研领域。它解决变电站时间偏差、5G 基站同步误差及高频交易延迟等问题,助力智能电网、5G 网络和科研实验。产品便携可靠,支持多协议,满足国家安全要求,为各行业提供精准时间同步解决方案。未来将探索量子通信与深空探测等领域,持续推动技术创新。
|
21天前
|
缓存 安全 Linux
Metasploit Pro 4.22.8-2025082101 (Linux, Windows) - 专业渗透测试框架
Metasploit Pro 4.22.8-2025082101 (Linux, Windows) - 专业渗透测试框架
80 0
|
3月前
|
Web App开发 开发框架 .NET
Playwright 自动化测试系列(6)| 第三阶段:测试框架集成​指南:参数化测试 + 多浏览器并行执行
Pytest 与 Playwright 集成可提升自动化测试效率,支持参数化测试、多浏览器并行执行及统一报告生成。通过数据驱动、Fixture 管理和并行优化,显著增强测试覆盖率与执行速度,适用于复杂 Web 应用测试场景。
|
4月前
|
安全 Linux 网络安全
Metasploit Pro 4.22.7-2025061201 (Linux, Windows) - 专业渗透测试框架
Metasploit Pro 4.22.7-2025061201 (Linux, Windows) - 专业渗透测试框架
123 3
Metasploit Pro 4.22.7-2025061201 (Linux, Windows) - 专业渗透测试框架
|
2月前
|
SQL 安全 Linux
Metasploit Pro 4.22.8-2025073001 (Linux, Windows) - 专业渗透测试框架
Metasploit Pro 4.22.8-2025073001 (Linux, Windows) - 专业渗透测试框架
118 0
|
3月前
|
测试技术 API C++
Playwright 自动化测试系列(7)| 第三阶段:测试框架集成​​Page Object 模式
本课程详解Playwright测试框架中的Page Object模式,通过电商登录-下单实战演示PO架构设计与高级技巧,结合Pytest实现多用户测试。重点解析PO模式提升代码复用性、降低维护成本的核心价值,并提供常见问题解决方案,助力构建高可维护性的自动化测试体系。
|
5月前
|
安全 Unix Linux
Metasploit Pro 4.22.7-2025052201 (Linux, Windows) - 专业渗透测试框架
Metasploit Pro 4.22.7-2025052201 (Linux, Windows) - 专业渗透测试框架
121 5
Metasploit Pro 4.22.7-2025052201 (Linux, Windows) - 专业渗透测试框架
|
3月前
|
Java 测试技术 API
自动化测试框架深度解析与选择指南
Apache JMeter是Apache组织基于Java开发的一款压力测试工具,旨在测试软件的性能承受能力。它支持多种协议测试及功能测试,提供灵活的断言创建能力,如同创建带断言的脚本来验证程序是否返回预期结果。

热门文章

最新文章