我很高兴地宣布,Object Bot 1.0.0正式发布了。
Object Bot 是什么?
Object Bot 是Java 的一个管理测试数据的程序库。
为什么要有 Object Bot?
随着测试数量增多,测试测试数据会散落在各个测试里,每个测试都要编写大量的测试数据初始化相关的代码,而且,通常测试数据还要满足一定的依赖关系,这会让测试数据的初始化代码大幅度增加。
Object Bot 就是为了解决这种困难而产生的。
添加依赖
在项目中添加相应的依赖,如果你的项目用的是 Maven,可以这样添加:
<dependency>
<groupId>com.github.dreamhead</groupId>
<artifactId>bot-junit5</artifactId>
<version>1.0.0</version>
</dependency>
如果是 Gradle,可以这样添加:
dependencies {
testImplementation(
"com.github.dreamhead:bot-junit5:1.0.0",
)
}
使用方式
假设我们有如下的一个测试数据类 Foo:
class Foo {
private String field1;
private String field2;
public Foo(String field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}
public String getField1() {
return this.field1;
}
public String getField2() {
return this.field2;
}
}
然后,编写一个 Initializer 初始化数据:
import com.github.dreamhead.bot.annotation.BotInitializer;
public class FooBotInitializer implements BotInitializer {
@Override
public void initializer(final ObjectBot bot) {
// Give a name to identify your Pojo.
bot.define("defaultFoo", new Foo("foo", "bar"));
}
}
接下来,就可以在测试中使用初始化好的数据了:
@ExtendWith(BotExtension.class)
// All test POJOs are initialized with FooBotInitializer.
@BotWith(FooBotInitializer.class)
public class FooTest {
// Use the name to identify your defined Pojo.
// It will be injected for each test.
@Bot("defaultFoo")
private Foo foo;
@Test
public void should_get_foo() {
assertThat(foo.getField1(), is("foo"));
}
}
如果需要在测试类中修改某些字段,为字段赋予新值,可以这么做:
@ExtendWith(BotExtension.class)
@BotWith(FooBotInitializer.class)
public class ModifiedFooTest {
@Bot(value = "defaultFoo")
// Customize field field2 with value blah
@StringField(name = "field2", value="blah")
private Foo foo;
@Test
public void should_get_foo() {
assertThat(foo.getField2(), is("blah"));
}
}
如果只是在单个测试中修改一个字段,可以使用 override:
@ExtendWith(BotExtension.class)
@BotWith(FooBotInitializer.class)
public class FooTest {
@Bot("defaultFoo")
private Foo foo;
@Test
public void should_get_foo() {
Foo newFoo = override(foo, field("field2").value("blah"));
assertThat(newFoo.getField2(), is("blah"));
}
就是这么简单,用起来吧!