与其他断言方法相比,使用AssertThat的好处

The Benefit of Using AssertThat Over Other Assert Methods

JUnit4.4发行说明讨论了在传统的assertXXX方法上使用assertThat的各种好处,我们将逐一逐步介绍。

1
assertThat([value], [matcher statement]);

可读性

新的语法使您可以用 subject verb object (应该是实际的期望)来思考(而不是像传统的那样)。断言)动词对象主题(断言等于预期的实际值)

现在,假设测试后变量(实际)应为100;这是两种版本的做法:

1
2
assertEquals(100, actual);
// assertEquals(expected, actual); In general

忘记正确的顺序并以相反的顺序键入很容易:

1
2
3
4
5
assertThat(actual, equalTo(100));
//OR
assertThat(actual, is(equalTo(100)));
//OR
assertThat(actual, is(100));

使用此版本,不会造成混乱;一切都非常清晰。它也更像一句话:" 声明实际值等于期望值100 "。

这是两个版本中不等于检查的方法:

1
assertFalse(expected.equals(actual));

由于没有assertNotEquals(除非它是自定义编码的),所以我们必须使用assertFalse并对两个变量进行等于。

1
2
3
assertThat(actual, is(not(equalTo(expected))));
//OR
assertThat(actual, is(not(expected)));

更好/更详细的故障消息

1
2
assertTrue("Number not between 1 and 3!", 1 < 5 && 5 < 3);
//java.lang.AssertionError: Number not between 1 and 3!

1
2
3
4
5
6
7
8
9
10
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;


assertThat(5 , allOf(greaterThan(1), lessThan(3)));
//java.lang.AssertionError:
Expected: (a value greater than <1> and a value less than <3>)
     but: a value less than <3> <5> was greater than <3>

类型安全

1
2
assertEquals("abc", 123);
//Compiles but fails

请注意,JUnit仅具有 hamcrest-core 依赖项。要充分利用匹配器,可以使用hamcrest-all,甚至可以使用AssertJ(Fluent Assertion API):

1
2
3
4
5
6
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;


assertThat(123, equalTo("abc"));
//Does not even compiles

断言

以下是AssertJ的一些示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// basic assertions
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron);

// chaining string specific assertions
assertThat(frodo.getName()).startsWith("Fro")
                           .endsWith("do")
                           .isEqualToIgnoringCase("frodo");

// collection specific assertions (there are plenty more)
// in the examples below fellowshipOfTheRing is a List<TolkienCharacter>
assertThat(fellowshipOfTheRing).hasSize(9)
                               .contains(frodo, sam)
                               .doesNotContain(sauron);

// as() is used to describe the test and will be shown before the error message
assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33);

请注意,如果图书馆所有者说他们更喜欢这样做,那么我会尽快而不是稍后进行切换。切换并不意味着您一次完成所有操作;这只是意味着,首先,您需要为新的测试用例提供新的方法。

参考文献

  • JUnit 4.4发行说明

  • 好文章