跳转到内容

使用 Trantor 进行单元测试

since 0.13

使用 Trantor 进行单元测试

在 Trantor 中,访问数据依赖模型元信息,即需要依赖 MetaStore 和 DataStore 两个服务分别存储元信息和协议转换以访问数据。 在此之前,我们想在一个单元测试中访问数据,需要在本地启动一套完整 trantor 环境,并且手动清理测试中产生的数据。这个操作比较繁琐,并且不符合单元测试定义。 所以在 0.13 我们提供了第一版测试支持,下面是使用说明。

实现方式

使用

  1. 首先需要依赖一个测试 jar 包,其中已经集成了 spring-boot-starter-test ,不需要依赖其他测试框架,开箱即用。
<dependency>
<groupId>io.terminus.trantor</groupId>
<artifactId>test-framework</artifactId>
<scope>test</scope>
</dependency>
  1. 下面我们开始编写测试:
@RunWith(TSpringRunner.class)
@SpringBootTest
public class UnitTest {
}

注意,我们使用 TSpringRunner 代替 spring-test 提供的 SpringRunner,其余配置与普通 spring-test 一致。 接下来就可以针对 DAO 编写测试逻辑:

@RunWith(TSpringRunner.class)
@SpringBootTest
public class UnitTest {
@Autowired
private CompanyRepo companyRepo;
@Test
public void testCreate() {
Company company = companyRepo.createWithRelation(new Company());
assertThat(company.getName()).isEmpty();
}
}
  1. 运行测试 在运行测试之前,需要准备一下环境,启动 DataStore 服务( 可以使用 trantor-cli 提供的 DataStore )。 环境准备完毕以后,由于测试会启动一个 spring context,因此会初始化一些 bean,这些 bean 需要配置一些环境变量,比如 DS_PORT、USER_MOCK 和 ACL_MOCK 等。 可以新建一个专门用于测试的 application-test.yml:
DS_PORT: 8081
USER_MOCK: true
ACL_MOCK: true
DUBBO_ENABLED: false
trantor:
mainModule: base

并在测试中启用它:

@RunWith(TSpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class UnitTest {
}

完成配置之后运行测试即可。 另外,我们没有限制注入环境变量的方式,也可以用别的方式,这里只是一个简单例子。

特性

  1. mock MetaStore,在测试过程中不依赖 MetaStore 服务
  2. 测试完成后自动清理测试数据
  3. 可以按需注册模块,如果一个业务模块依赖了很多其他模块,在测试中我们也会注册依赖模块的模型,并在 db 里建立对应的 schema。 这样会导致测试的执行速度下降,如果在一个或者一组测试中,只需要依赖少量模块,也可以手动通过注解申明:
@RunWith(TSpringRunner.class)
@SpringBootTest
@ActiveModule("base")
public class UnitTest {
}

在测试类上申明 @ActiveModule("base") ,这样在 UnitTest 中的所有测试,都只会使用 base 模块。 该注解也同样可以在测试方法上申明:

@RunWith(TSpringRunner.class)
@SpringBootTest
public class UnitTest {
@Autowired
private CompanyRepo companyRepo;
@Test
@ActiveModule("base")
public void testCreate() {
Company company = companyRepo.createWithRelation(new Company());
assertThat(company.getName()).isEmpty();
}
}

testCreate() 这个测试来说,效果与在类上申明注解相同。

问题

由于 DataStore 的执行逻辑全部在服务端,逻辑又比较复杂,因此这版本测试还是依赖 DataStore,后面版本 DataStore Client 做重以后考虑支持完整的 mock。