Google Truth 是一個在測試時,做 assert (斷言)的 library, 他比原生的 junit 優異的地方在於可讀性

官方的例子:

assertTrue(blah > 5);       // junit
ASSERT.that(blah).isMoreThan(5);        // Google Truth

不過文件好像有點久沒更新,因為現在 ASSERT.that 都已經改成 assertThat 了。 Android Studio 也會自動 static import。所以我下面就用 assertThat 了。

以下就來持續整理一些我正在用的。

Booleans

assertThat(something).isTrue();
assertThat(something).isFalse();

Numerics and Comparables

assertThat(foo).isEqualTo(5);
assertThat(bar).isNotEqualTo(5);

Strings

assertThat(aString).contains("blah");
assertThat(aString).startsWith("foo");
assertThat(aString).endsWith("bar");

Collections

assertThat(collection).hasSize(5);
assertThat(anIterable).isEmpty();

assertThat(collectionA).contains(q);
assertThat(collectionA).containsAllOf(a, b, c);
assertThat(collectionA).containsExactly(a, b, c, d);

assertThat(collectionA).containsAllOf(a, b, c).inOrder();
  • Maps
assertThat(map).containsKey("foo");
assertThat(map).containsEntry("foo", "bar");
assertThat(map).doesNotContainKey("foo");

其它

  • Labeling the subject
Foo foo = null;
ASSERT.that(something).named("foo").isNotNull();

// output:  Not true that null reference "foo" is not null.

Comments

comments powered by Disqus
Copyright © 2013 Andro Chen
Powered by Logdown and Greyshade
Favicon from The Noun Project