首先看一组对比,比如说我们要测试的结果是一个Linearlaout
AssertJ Android:
assertThat(layout).isVisible()
.isVertical()
.hasChildCount(4)
.hasShowDividers(SHOW_DIVIDERS_MIDDLE);
Regular JUnit:
assertEquals(View.VISIBLE, layout.getVisibility());
assertEquals(VERTICAL, layout.getOrientation());
assertEquals(4, layout.getChildCount());
assertEquals(SHOW_DIVIDERS_MIDDLE, layout.getShowDividers());
Regular AssertJ:
assertThat(layout.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(layout.getOrientation()).isEqualTo(VERTICAL);
assertThat(layout.getChildCount()).isEqualTo(4);
assertThat(layout.getShowDividers()).isEqualTo(SHOW_DIVIDERS_MIDDLE);
从形式上,使用上更加方便。
从输出结果上看,输出结果更加直接可见。
AssertJ Android: Expected visibility but was .
Regular JUnit Expected: but was:
Regular AssertJ: Expected: <8> but was: <4>
所以接下来我们来看看 Assert Android如何来使用。
1首先写一个待测试的数据结构
public class Draft{
private String id;//草稿的唯一标识id
private String uid ;//发送账号uid,以区别不同账号的草稿
private int type;//保存的类型
private String displayedTitle;//展示标题内容
}
2 首先我们来自定义一个断言类:
public class DraftAssert extends AbstractAssert{
public DraftAssert
(Draft draft){
super(draft,DraftAssert.class);}
}
public static DraftAssert
assertThat(Draft draft){
return new
DraftAssert (draft);}
public DraftAssert hasDisplayedName(String name){
isNotNull();
if (!draft.getDisplayedTitle().equals(name)){
failWithMessage(("Expected character's name to be but was ", name,
draft.getDisplayedTitle());)
return this;
}
}
3、使用的时候
DraftAssert.assertThat(draft).hasDisplayedName("@罗浩");
如果导入DraftAssert.assertThat静态导入的话,你还可以直接使用
assertThat(draft).hasDisplayedName("@罗浩");