From b436eab366b6a0d6bd75500f94633c97e86d4154 Mon Sep 17 00:00:00 2001 From: Dmitry Andreychuk Date: Mon, 6 Jul 2015 22:55:01 +0300 Subject: [PATCH] GROOVY-7474: Difference between junit3 and junit 4 shouldFail {...} not described in docs --- src/spec/doc/core-testing-guide.adoc | 10 ++++++++++ .../test/testingguide/JUnit4ExampleTests.groovy | 17 +++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/spec/doc/core-testing-guide.adoc b/src/spec/doc/core-testing-guide.adoc index 1e893d960b1..3d993b9e914 100644 --- a/src/spec/doc/core-testing-guide.adoc +++ b/src/spec/doc/core-testing-guide.adoc @@ -471,6 +471,16 @@ As can be seen in the example above, the static methods found in `GroovyAssert` with the introduction of the power assertion statement, it turned out to be _good practice to rely on assertion statements_ instead of using the JUnit assertion methods with the improved message being the main reason. +It is worth mentioning that `GroovyAssert.shouldFail` is not absolutely identical to `GroovyTestCase.shouldFail`. While +`GroovyTestCase.shouldFail` returns the exception message, `GroovyAssert.shouldFail` returns the exception itself. It +takes a few more keystrokes to get the message, but in return you can access other properties and methods of the +exception: + +[source,groovy] +---- +include::{projectdir}/src/spec/test/testingguide/JUnit4ExampleTests.groovy[tags=should_fail_return,indent=0] +---- + == Testing with Spock Spock is a testing and specification framework for Java and Groovy applications. What makes it stand out from the diff --git a/src/spec/test/testingguide/JUnit4ExampleTests.groovy b/src/spec/test/testingguide/JUnit4ExampleTests.groovy index 969ab08b630..dfb4cf7f7fc 100644 --- a/src/spec/test/testingguide/JUnit4ExampleTests.groovy +++ b/src/spec/test/testingguide/JUnit4ExampleTests.groovy @@ -31,5 +31,22 @@ class JUnit4ExampleTests { numbers.get(4) } } + + // end::junit4_example[] + + // tag::should_fail_return[] + @Test + void shouldFailReturn() { + def e = shouldFail { + throw new RuntimeException('foo', + new RuntimeException('bar')) + } + assert e instanceof RuntimeException + assert e.message == 'foo' + assert e.cause.message == 'bar' + } + // end::should_fail_return[] + + // tag::junit4_example[] } // end::junit4_example[]