在我以前的测试文章中,我描述了如何使用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