Groovy has excellent support for Testing with Unit Testing (GroovyTestCase adds extra capabilities to TestCase from JUnit 3.8.2) and Mocking capabilities built right in. Currently, there are no special Groovy extensions for JUnit 4 but it's easy to use so long as you are using Groovy 1.5+ and Java 5+ (a requirement for annotations/Junit 4.x). Here are some examples.

Make sure you are using at least Groovy 1.5 (we used 1.5.6) and JUnit 4.x (we used 4.4).

Simple Example

Let's test some of the built-in arithmetic operators in Groovy.

Alternatively, one could use the shouldFail method as follows:

Our test class includes two tests additionIsWorking and divideByZero. The second of these is expected to fail with an ArithmeticException exception.

Running the test gives:

Hamcrest Matching

You can use the Hamcrest matchers that come with JUnit 4.4 and above like this:

The first test uses the matchers. You can see by the second test, that native Groovy assertions are usually going to do the job just as well if not better in the Groovy world.

Parameterized Testing

JUnit 4.x includes the ability to have parameterized tests. Suppose we want to test the following program: