There are a two approaches to effectively test your code in CQ5 – either outside of CQ5 using standard unit tests instantiated from your build tool (i.e. maven). While this approach will cover most simple functionality, the need will quickly arise to execute unit tests within CQ5/Sling/OSGi.

Testing outside of CQ5

In addition to your standard junit tests, you can grab a hold of the CRX repository and start writing some basic tests against that. As you can see in the following example, you ca even wrap the JCR-repository in its Sling equivalent:

package com.jtoee.cq.test;

import org.a~pache.jackrabbit.commons.JcrUtils;

import org.apache.sling.jcr.api.SlingRepository;

import org.junit.Test;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import javax.jcr.Repository;

import javax.jcr.RepositoryException;

publicclass SimpleTest {

private Logger log = LoggerFactory.getLogger(SimpleTest.class);

@Test

publicvoid runTest() {

try {

log.debug("Connecting to respository");

Repository repository = JcrUtils.

getRepository("http://localhost:4502/crx/server");

SlingRepository slingRepo =

new RepositoryUtil.RepositoryWrapper(repository);

log.debug("Retrieved sling repository");

// .. do something

} catch (RepositoryException e) {

log.debug("Exception retrieving repository.", e);

}

}

}

Testing within CQ5

If you’ve dug into CQ5 a little more, you’ve noticed the the power of the OSGi container and have probably started writing a lot of components (services) and wired them together via dependency injection. Luckily there’s a very easy way to run unit tests directly in the container and even use the OSGi-style dependency injection directly in your test, allowing you not only to write simple unit tests but also more involved automated integration tests.