Testing with JUnit

If you want to write JUnit tests for your application, you can use the following TestRunner which will initialize a liferay context such that you are able to use for example liferay services. However this approach makes it necessary to add portal-impl.jar as a dependency.

public class LiferayJUnitTestRunner
extends BlockJUnit4ClassRunner {

public LiferayIntegrationJUnitTestRunner(Class clazz)
throws InitializationError {

super(clazz);

if (System.getProperty("external-properties") == null) {
System.setProperty("external-properties", "portal-test.properties");
}

InitUtil.initWithSpring();

_testContextHandler = new TestContextHandler(clazz);
}

@Override
protected Statement withAfters(
FrameworkMethod frameworkMethod, Object instance, Statement statement) {

Statement withAftersStatement = super.withAfters(frameworkMethod, instance, statement);

return new RunAfterTestMethodCallback(
instance, frameworkMethod.getMethod(), withAftersStatement,
_testContextHandler);
}

@Override
protected Statement withBefores(
FrameworkMethod frameworkMethod, Object instance, Statement statement) {

Statement withBeforesStatement = super.withBefores(frameworkMethod, instance, statement);

return new RunBeforeTestMethodCallback(
instance, frameworkMethod.getMethod(), withBeforesStatement,
_testContextHandler);
}

public static void run(Class clazz){
Request request=Request.classWithoutSuiteMethod(clazz);
Runner runner=request.getRunner();
RunNotifier notifier=new RunNotifier();
runner.run(notifier);
}

private TestContextHandler _testContextHandler;
}
A sample TestCase looks like that:
@RunWith(LiferayIntegrationJUnitTestRunner.class)
public class SampleTestCase{
@Test
public void testSample() throws Exception {
List users = UserLocalServiceUtil.getUsers(-1, -1);
Assert.assertNotNull(users);
}
}

Leave a Reply