Getting a QC test coverage report from JUnit

I’ve written a quick example that shows how to use custom annotations on JUnit tests to map them to Quality Center test cases.

You can create an annotation called “QCTestCases” and add it to your JUnit tests like this:

package oneshore.example.qcintegration;

import static org.junit.Assert.*;
import org.junit.Test;

public class MyTest extends TestBase {
	@Test
	@QCTestCases(covered={"QC-TEST-1", "QC-TEST-2"}, related={"QC-TEST-3"})
	public void testSomething() {
		assertTrue(true);
	}
}

The annotation is a simple interface:

package oneshore.example.qcintegration;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface QCTestCases {
	String[] covered();
	String[] related();
}

And the base class uses reflection to discover if the annotation has been added for the test case. You can then use it to report the coverage:

package oneshore.example.qcintegration;

import java.lang.reflect.Method;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;

public class TestBase {
	@Rule public TestName testName = new TestName();
	
	QCTestCases qcTestCases;
	
	@Before
	public void getQCTestCoverage() {
		try {
			Method m = this.getClass().getMethod(testName.getMethodName());
			
			if (m.isAnnotationPresent(QCTestCases.class)) {
				qcTestCases = m.getAnnotation(QCTestCases.class);
			} 
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}
	
	@After
	public void writeCoverageReport() {
		StringBuilder result = new StringBuilder();
		result.append(testName.getMethodName());
		result.append(",");
		
		for (String qcTestId : qcTestCases.covered())
		{
			result.append(qcTestId);
			result.append(",");
		}
		
		System.out.println("qc tests covered: " + result);
	}
}

The trick is using the “Rule” to get the testName which is available in Junit 4.5+ to get the currently executing test method.

It’s probably a bit unnecessarily complex of an example, since “related” is something extra I added for my own analysis.

This code is available on the QCIntegration repository on github.

2 thoughts on “Getting a QC test coverage report from JUnit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s