Skip to content

Instantly share code, notes, and snippets.

@jakubkulhan
Created March 31, 2016 12:26
Show Gist options
  • Save jakubkulhan/957cd3fbddebe1a77133e2e9a761b6d1 to your computer and use it in GitHub Desktop.
Save jakubkulhan/957cd3fbddebe1a77133e2e9a761b6d1 to your computer and use it in GitHub Desktop.
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.reflections.Reflections;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.junit.Assert.fail;
@RunWith(Parameterized.class)
public class CoverageTest {
private Class<?> component;
public CoverageTest(Class<?> component) {
this.component = component;
}
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() {
final Reflections reflections = new Reflections(CoverageTest.class.getPackage().getName());
return new HashSet<Class<?>>() {{
addAll(reflections.getTypesAnnotatedWith(Controller.class));
addAll(reflections.getTypesAnnotatedWith(RestController.class));
}}
.stream()
.map((klass) -> new Object[]{klass})
.collect(Collectors.toList());
}
@Test
public void testCoverage() throws Exception {
String failMessage = "";
String testClassName = component.getName() + "Test";
try {
Class<?> testClass = Class.forName(testClassName);
for (Method method : component.getDeclaredMethods()) {
if (!method.getName().endsWith("Action") && !method.getName().startsWith("on")) {
continue;
}
try {
testClass.getDeclaredMethod("test" + method.getName().substring(0, 1).toUpperCase() + method.getName().substring(1));
} catch (NoSuchMethodException e) {
failMessage += "Method " + component + "." + method.getName() + "() not covered.\n";
}
}
} catch (ClassNotFoundException e) {
failMessage += "Class " + component + " not covered.\n";
}
if (failMessage.length() > 0) {
fail(failMessage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment