Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 9 Next »

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).

Simple Example

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:

Hamcrest Matching

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.

Parameterized Testing

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:

Theory Tests

You can use the experimental Theory tests as follows:

  • No labels