Groovy has excellent support for Unit Testing with JUnit 3.8.2 and Mocking capabilties built right in. Currently, special support doesn't exist for JUnit 4 but its easy to use so long as you are using Groovy 1.1 (currently in beta) and Java 5+ (a requirement for annotations/Junit 4.x). Here is an example.
Make sure you are using Groovy 1.1 (we used beta-2) and JUnit 4.x (we used 4.4).
Let's test some of the built-in arithmetic operators in Groovy.
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:
You can use the Hamcrest matchers that come with JUnit 4.4 and above like this:
Though as you can see by the second test, the native Groovy assertions are usually going to do the job just as good if not better.
JUnit 4.x includes the ability to have parameterized tests. Suppose we want to test the following program:
Here is what your code might look like. This example uses parameterization.
The output will look something like this:
You can use the experimental Theory tests as follows: