Friday, November 26, 2010

STS and Grails - running JUnit tests from IDE

Hi folks!

Have you been wondering how to run JUnit 4 tests under STS so that the the tests are recognized and executed properly?

junit.framework.AssertionFailedError: No tests found in

I guess most of you writing tests for your Grails application have seen this one under Idea or STS. The IDE just doesn't see the right tests by itself... But there's hope!

Here's a definition of a class that when used in conjunction with the @RunWith annotation allows the IDE to run those test properly:
package com.aplaline.example.test;

import org.codehaus.groovy.grails.test.GrailsTestTargetPattern;
import org.codehaus.groovy.grails.test.junit4.runner.GrailsTestCaseRunner;

@SuppressWarnings("rawtypes")
public class GrailsJUnit4Runner extends GrailsTestCaseRunner {
public GrailsJUnit4Runner(Class testClass) {
super(testClass, new GrailsTestTargetPattern[0]);
}
}

And here's an example test that uses it:
package com.aplaline.example

import grails.test.*

import org.junit.Test;
import org.junit.runner.RunWith;
import com.aplaline.example.test.GrailsJUnit4Runner;

@RunWith(GrailsJUnit4Runner)
class CalculatorServiceTests extends GrailsUnitTestCase {
@Test
void canAddTwoNumbers() {
// given
def service = new CalculatorService()

// when
def actual = service.sum(1, 2)

// then
assert actual == 3
}
}

See - that wasn't hard, was it?

I hope it'll help you out test your code more efficiently :)

Have fun!!!

No comments: