liangzai-cool / hamcrest

Automatically exported from code.google.com/p/hamcrest
0 stars 0 forks source link

Add an assertThat(String message, Boolean assertion) method #15

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Several times I find myself trying to use assertThat to test a method that
returns boolean.  I've noticed other people make the same mistake as well.

Original issue reported on code.google.com by nat.pr...@gmail.com on 24 Jun 2007 at 3:12

GoogleCodeExporter commented 9 years ago
Hmm, how would this read? I can see a case for a simple assertThat(Boolean 
assertion). e.g. assertThat
(myList.isEmpty()) but not assertThat("myList should be empty", 
myList.isEmpty()). Then again, I suppose the 
failure message wouldn't by much good otherwise - expected true got false.

I previously tried the concept of a Consequence, where a Consequence has a 
manifest() method that is called 
when assertThat fails. I had a utility method otherwise() which returned a 
FailureMessage Consequence. Then 
you can do

assertThat(myList.isEmpty(), otherwise("myList unexpectedly contains data"));

also in the more usual form:

assertThat(myList, hasItem(x), otherwise("x is missing from myList"));

Original comment by rchatley@gmail.com on 24 Jun 2007 at 3:39

GoogleCodeExporter commented 9 years ago
That seems overkill.  The string can be optional (where the test name has enough
information) or can add higher-level context, such as:

assertThat("no unsheared sheep",
           sheep.isEmpty());

Original comment by nat.pr...@gmail.com on 24 Jun 2007 at 4:59

GoogleCodeExporter commented 9 years ago
This would also work around an annoying artefact of the JUnit assertion 
methods: that
assertFalse makes tests hard to read.

E.g.

  assertFalse("the list should contain items", list.isEmpty());

On quick reading that is very confusing because it appears to stating that "the 
list
should contain items" must be false when actually it must be true.

Using assertThat forces you the assertion and message to agree:

  assertThat("the list should contain items", !list.isEmpty());

Original comment by nat.pr...@gmail.com on 30 Jul 2007 at 1:44

GoogleCodeExporter commented 9 years ago

Original comment by nat.pr...@gmail.com on 30 Jul 2007 at 2:01