使用TestContainers提高测试性能

本文探讨了如何通过改变TestContainers的使用方式来减少数据库测试的开销,从而提高测试性能。通过在JUnit测试类级别启动和重用Docker容器,尽管失去了测试并行化,但显著减少了构建时间,特别是对于包含多个测试方法的测试类,执行速度可从几分钟缩短到几秒钟。
摘要由CSDN通过智能技术生成

在我以前的测试文章中,我描述了如何使用TestContainers为数据库测试提供现实的测试环境。 此评论显示了缺点:

…如上所述,似乎总是有一些缺点。 在这种情况下,启动Docker映像及其包含的所有内容的开销将增加您的总体构建时间。

提醒一下,这是TestContainer特定的代码。 注意实例成员postgres ,以及根据每个方法重新初始化它的JUnit Rule

package be.objectify.tcexample.db;

import be.objectify.tcexample.AbstractUserDaoTest;
import be.objectify.tcexample.UserDao;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.testcontainers.containers.PostgreSQLContainer;
import play.db.Database;

public class JooqUserDaoTest extends AbstractUserDaoTest implements DbTestSupport,
                                                                    TestData {

    @Rule
    public PostgreSQLContainer postgres = new PostgreSQLContainer();
    
    private Database database;
    
    @Before
    public void setup() throws Exception {
        // the database has all evolutions applied
        database = create(postgres); 
        // load some test data
        loadTestData(database); 
    }

    @After
    public void tearDown() {
        destroy(database);
    }

    @Override
    public UserDao dao() {
        return new JooqUserDao(database);
    }
}

鉴于测试持续时间的巨大增加是由Docker容器启动时间导致的,因此我们可以改用JUnit ClassRule启动一个容器,并将其重新用于类中的每个测试。 这意味着您不再应该并行运行这些测试,但是性能提升将大大超过测试并行化。

package be.objectify.tcexample.db;

import be.objectify.tcexample.AbstractUserDaoTest;
import be.objectify.tcexample.UserDao;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.testcontainers.containers.PostgreSQLContainer;
import play.db.Database;

public class FasterJooqUserDaoTest extends AbstractUserDaoTest implements DbTestSupport,
                                                                          TestData {

    @ClassRule
    public static PostgreSQLContainer postgres = new PostgreSQLContainer();
    
    private Database database;
    
    @Before
    public void setup() throws Exception {
        database = create(postgres); 
        loadTestData(database); 
    }

    @After
    public void tearDown() {
        destroy(database);
    }

    @Override
    public UserDao dao() {
        return new JooqUserDao(database);
    }
}

节省的时间取决于类中测试方法的数量。 我有一些测试类,每个类最多包含30个测试,在这种情况下,执行时间从几分钟缩短到几秒钟。 更改几行代码也不错。

翻译自: https://www.javacodegeeks.com/2017/05/boosting-test-performance-testcontainers.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值