JUnit4 Tests in Groovy
Posted on March 21, 2008 by Scott Leberknight
On my current (Java-based) project we now write all new unit tests in Groovy, though there are a lot of legacy Java tests still out there that we haven't had time or felt the need to convert to Groovy-based tests. There are also several base test classes, also written in Java, that provide some nice set up and tear down code for certain classes of test. I happened to be testing a web controller and realized I needed (or rather, wanted) to make use of the existing AbstractViewControllerTest
base class, which is written in Java, uses JUnit4 annotations, and provides, among other things, code that creates and sets up a simulated authenticated user for the controller along with a bunch of other stuff like mock requests, responses, session, helper methods, etc. So, the problem was that I needed to extend AbstractViewControllerTest
and not GroovyTestCase
, and initially got all bent out of shape about having to choose to write the test in Java and extend the base test or write it in Groovy extending GroovyTestCase
and having to redo the stuff already provided by the base class.
Thankfully about that time Steve reminded me nicely that you can mix-and-match Groovy and JUnit4 annotations just fine since Groovy has now sported annotation support for a while now (since ~1.1 I think). So I can simply write the test in Groovy, extend the base test class, and use JUnit4 annotations to get exactly what I want. What's the point? Just remember that when writing tests in Groovy there is nothing that says you must extend GroovyTestCase
and that you can use JUnit4 in Groovy tests. So for example you could have a Groovy test like this:
class MyTest extends TestBaseClass { @Before void doSetup() { ... } @Test void testSomething() { ... } @Test(expected = IllegalArgumentException) void testBadThing() { ... } }
This way you can extend some other class if you choose, and get all the normal JUnit4 stuff. Since you are not extending GroovyTestCase
one thing that is missing is shouldFail()
so instead you use the "expected" parameter in your @Test
annotation when you want to verify a specific type of exception was thrown.