下面列出了怎么用org.junit.runner.RunWith的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @return true if {@param cls} is {@link JUnit4} annotated.
*/
protected boolean isJUnit4TestClass(Class cls) {
// Need to find test classes, otherwise crashes with b/11790448.
if (!cls.getName().endsWith("Test")) {
return false;
}
// Check the annotations.
Annotation annotation = cls.getAnnotation(RunWith.class);
if (annotation != null) {
RunWith runWith = (RunWith) annotation;
Object value = runWith.value();
if (value.equals(JUnit4.class) || value.equals(Suite.class)) {
return true;
}
}
return false;
}
DesugarRuleBuilder(Object testInstance, MethodHandles.Lookup testInstanceLookup) {
this.testInstance = testInstance;
this.testInstanceLookup = testInstanceLookup;
Class<?> testClass = testInstance.getClass();
androidRuntimeJarJvmFlagValue = getExplicitJvmFlagValue(ANDROID_RUNTIME_JAR_JVM_FLAG_KEY);
jacocoAgentJarJvmFlagValue = getExplicitJvmFlagValue(JACOCO_AGENT_JAR_JVM_FLAG_KEY);
if (testClass != testInstanceLookup.lookupClass()) {
errorMessenger.addError(
"Expected testInstanceLookup has private access to (%s), but get (%s). Have you"
+ " passed MethodHandles.lookup() to testInstanceLookup in test class?",
testClass, testInstanceLookup.lookupClass());
}
if (!testClass.isAnnotationPresent(RunWith.class)) {
errorMessenger.addError(
"Expected a test instance whose class is annotated with @RunWith. %s", testClass);
}
injectableClassLiterals =
findAllInjectableFieldsWithQualifier(testClass, DynamicClassLiteral.class);
injectableAsmNodes = findAllInjectableFieldsWithQualifier(testClass, AsmNode.class);
injectableMethodHandles =
findAllInjectableFieldsWithQualifier(testClass, RuntimeMethodHandle.class);
injectableJarEntries = findAllInjectableFieldsWithQualifier(testClass, RuntimeJarEntry.class);
}
@Test
public void scanTest()
{
ClassScanner scanner = ClassScanner.builder("com.github.harbby.gadtry")
.subclassOf(Serializable.class)
.annotated(RunWith.class)
.classLoader(this.getClass().getClassLoader())
.filter(aClass -> !aClass.isEnum())
.scan();
Set<Class<?>> classSet = scanner.getClasses();
Assert.assertTrue(!classSet.isEmpty());
Assert.assertTrue(classSet.contains(ClassScannerTest.class));
}
@Test
public void getFilterTest()
{
ClassScanner scanner = ClassScanner.builder("com.github.harbby.gadtry").scan();
Set<Class<?>> classSet = scanner.getClassWithAnnotated(RunWith.class, Deprecated.class);
Assert.assertTrue(classSet.contains(ClassScannerTest.class));
classSet = scanner.getClassWithSubclassOf(Serializable.class);
Assert.assertTrue(classSet.contains(ClassScannerTest.class));
for (Class<?> aClass : classSet) {
Assert.assertTrue(Serializable.class.isAssignableFrom(aClass));
}
}
private boolean isColaTestClass(Class<?> testClzz){
RunWith runWith = testClzz.getAnnotation(RunWith.class);
if(runWith == null){
return false;
}
if(runWith.value().equals(ColaTestRunner.class)
|| runWith.value().equals(ColaTestUnitRunner.class)){
return true;
}
return false;
}
/**
* Runs the guided fuzzing loop for a resolved class.
*
* <p>The test class must be annotated with <tt>@RunWith(JQF.class)</tt>
* and the test method must be annotated with <tt>@Fuzz</tt>.</p>
*
* <p>Once this method is invoked, the guided fuzzing loop runs continuously
* until the guidance instance decides to stop by returning <tt>false</tt>
* for {@link Guidance#hasInput()}. Until the fuzzing stops, this method
* cannot be invoked again (i.e. at most one guided fuzzing can be running
* at any time in a single JVM instance).</p>
*
* @param testClass the test class containing the test method
* @param testMethod the test method to execute in the fuzzing loop
* @param guidance the fuzzing guidance
* @param out an output stream to log Junit messages
* @throws IllegalStateException if a guided fuzzing run is currently executing
* @return the Junit-style test result
*/
public synchronized static Result run(Class<?> testClass, String testMethod,
Guidance guidance, PrintStream out) throws IllegalStateException {
// Ensure that the class uses the right test runner
RunWith annotation = testClass.getAnnotation(RunWith.class);
if (annotation == null || !annotation.value().equals(JQF.class)) {
throw new IllegalArgumentException(testClass.getName() + " is not annotated with @RunWith(JQF.class)");
}
// Set the static guided instance
setGuidance(guidance);
// Register callback
SingleSnoop.setCallbackGenerator(guidance::generateCallBack);
// Create a JUnit Request
Request testRequest = Request.method(testClass, testMethod);
// Instantiate a runner (may return an error)
Runner testRunner = testRequest.getRunner();
// Start tracing for the test method
SingleSnoop.startSnooping(testClass.getName() + "#" + testMethod);
// Run the test and make sure to de-register the guidance before returning
try {
JUnitCore junit = new JUnitCore();
if (out != null) {
junit.addListener(new TextListener(out));
}
return junit.run(testRunner);
} finally {
unsetGuidance();
}
}
@Test
public void imports_urls_of_jars() {
Set<URL> urls = newHashSet(urlOf(Test.class), urlOf(RunWith.class));
assumeTrue("We can't completely ensure that this will always be taken from a JAR file, though it's very likely",
"jar".equals(urls.iterator().next().getProtocol()));
JavaClasses classes = new ClassFileImporter().importUrls(urls)
.that(DescribedPredicate.not(type(Annotation.class))); // NOTE @Test and @RunWith implement Annotation.class
assertThat(classes).as("Number of classes at the given URLs").hasSize(2);
}
@Override
protected Annotation[] getRunnerAnnotations() {
Annotation[] allAnnotations = super.getRunnerAnnotations();
Annotation[] annotationsWithoutRunWith = new Annotation[allAnnotations.length - 1];
int i = 0;
for (Annotation annotation: allAnnotations) {
if (!annotation.annotationType().equals(RunWith.class)) {
annotationsWithoutRunWith[i] = annotation;
++i;
}
}
return annotationsWithoutRunWith;
}
@Override
protected Annotation[] getRunnerAnnotations() {
Annotation[] allAnnotations = super.getRunnerAnnotations();
Annotation[] annotationsWithoutRunWith = new Annotation[allAnnotations.length - 1];
int i = 0;
for (Annotation annotation: allAnnotations) {
if (!annotation.annotationType().equals(RunWith.class)) {
annotationsWithoutRunWith[i] = annotation;
++i;
}
}
return annotationsWithoutRunWith;
}
@Test
public void testClassWithoutPersistenceContextField() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
assertThat(failure.getException().getMessage(), containsString("EntityManagerFactory or EntityManager field annotated"));
}
@Test
public void testClassWithMultiplePersistenceContextFields() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar em1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em1");
em1Field.annotate(PersistenceContext.class);
final JFieldVar em2Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em2");
em2Field.annotate(PersistenceContext.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
assertThat(failure.getException().getMessage(), containsString("Only single field is allowed"));
}
@Test
public void testClassWithMultiplePersistenceUnitFields() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf1");
emf1Field.annotate(PersistenceUnit.class);
final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf2");
emf2Field.annotate(PersistenceUnit.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
assertThat(failure.getException().getMessage(), containsString("Only single field is allowed"));
}
@Test
public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
emf1Field.annotate(PersistenceContext.class);
final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
emf2Field.annotate(PersistenceUnit.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
assertThat(failure.getException().getMessage(), containsString("either @PersistenceUnit or @PersistenceContext"));
}
@Test
public void testClassWithPersistenceContextFieldOfWrongType() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "em");
emField.annotate(PersistenceContext.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
assertThat(failure.getException().getMessage(), containsString("annotated with @PersistenceContext is not of type EntityManager"));
}
@Test
public void testClassWithPersistenceUnitFieldOfWrongType() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "emf");
emField.annotate(PersistenceUnit.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
assertThat(failure.getException().getMessage(),
containsString("annotated with @PersistenceUnit is not of type EntityManagerFactory"));
}
@Test
public void testClassWithPersistenceContextWithoutUnitNameSpecified() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
emField.annotate(PersistenceContext.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(JpaUnitException.class));
assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
@Test
public void testClassWithPersistenceUnitWithoutUnitNameSpecified() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
emField.annotate(PersistenceUnit.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
final JpaUnitRunner runner = new JpaUnitRunner(cut);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
verify(listener).testFailure(failureCaptor.capture());
final Failure failure = failureCaptor.getValue();
assertThat(failure.getException().getClass(), equalTo(JpaUnitException.class));
assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
@Test
public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class);
jAnnotation.param("unitName", "test-unit-1");
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final JpaUnitRunner runner = new JpaUnitRunner(cut);
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
verify(listener).testStarted(descriptionCaptor.capture());
assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
verify(listener).testFinished(descriptionCaptor.capture());
assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
@Test
public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class);
jAnnotation.param("unitName", "test-unit-1");
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final JpaUnitRunner runner = new JpaUnitRunner(cut);
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
verify(listener).testStarted(descriptionCaptor.capture());
assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
verify(listener).testFinished(descriptionCaptor.capture());
assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
@Test
public void testJpaUnitRunnerAndJpaUnitRuleFieldExcludeEachOther() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class);
jAnnotation.param("unitName", "test-unit-1");
final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
ruleField.annotate(Rule.class);
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
try {
// WHEN
new JpaUnitRunner(cut);
fail("InitializationError expected");
} catch (final InitializationError e) {
// expected
assertThat(e.getCauses().get(0).getMessage(), containsString("exclude each other"));
}
}
private TypeSpec classTest(ClassName className, List<MethodSpec> methodSpecs) {
String methodName = Introspector
.decapitalize(className.simpleName());
MethodSpec abstractMethodInstanceToTest = methodBuilder(methodName)
.addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED)
.returns(className)
.build();
FieldSpec exception = FieldSpec.builder(ExpectedException.class, "exception")
.addAnnotation(Rule.class)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.initializer("$T.none()", ExpectedException.class)
.build();
return TypeSpec.classBuilder(className.simpleName() + "Test_")
.addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC)
.addMethod(abstractMethodInstanceToTest)
.addField(exception)
.addAnnotation(AnnotationSpec.builder(Generated.class)
.addMember("value", "$S", MockeryProcessor.class.getCanonicalName())
.addMember("comments", "$S", CMessages.codeGenerateWarning())
.build())
.addAnnotation(AnnotationSpec.builder(RunWith.class)
.addMember("value", "$T.class", OrderedRunner.class)
.build())
.addMethods(methodSpecs)
.build();
}
@Test
@Ignore
public void sqlIntegrationMembershipComplete() {
ImmutableSet<String> sqlDependentTests;
try (ScanResult scanResult =
new ClassGraph().enableAnnotationInfo().whitelistPackages("google.registry").scan()) {
sqlDependentTests =
scanResult.getClassesWithAnnotation(RunWith.class.getName()).stream()
.filter(clazz -> clazz.getSimpleName().endsWith("Test"))
.map(clazz -> clazz.loadClass())
.filter(SqlIntegrationMembershipTest::isSqlDependent)
.map(Class::getName)
.collect(ImmutableSet.toImmutableSet());
}
ImmutableSet<String> declaredTests =
Stream.of(SqlIntegrationTestSuite.class.getAnnotation(SuiteClasses.class).value())
.map(Class::getName)
.collect(ImmutableSet.toImmutableSet());
SetView<String> undeclaredTests = Sets.difference(sqlDependentTests, declaredTests);
expect
.withMessage(
"Undeclared sql-dependent tests found. "
+ "Please add them to SqlIntegrationTestSuite.java.")
.that(undeclaredTests)
.isEmpty();
SetView<String> unnecessaryDeclarations = Sets.difference(declaredTests, sqlDependentTests);
expect
.withMessage("Found tests that should not be included in SqlIntegrationTestSuite.java.")
.that(unnecessaryDeclarations)
.isEmpty();
}
/**
* @param clazz Test class that is running.
* @return the number of parameters for this given test class. If the test is not parameterized or
* if there is any issue determining the number of parameters, returns 1.
*/
@VisibleForTesting
static int getNumParameters(Class<?> clazz) {
RunWith[] runWiths = clazz.getAnnotationsByType(RunWith.class);
boolean testParameterized = runWiths != null && Arrays.stream(runWiths).anyMatch(
(r) -> r.value().equals(Parameterized.class));
if (!testParameterized) {
return 1;
}
for (Method method : clazz.getMethods()) {
if (!isParametersMethod(method)) {
continue;
}
// Found the parameters method. Figure out the number of parameters.
Object parameters;
try {
parameters = method.invoke(clazz);
} catch (IllegalAccessException | InvocationTargetException e) {
LOG.warn("Error invoking parameters method {} in test class {}",
method.getName(), clazz, e);
continue;
}
if (parameters instanceof List) {
return ((List) parameters).size();
} else if (parameters instanceof Collection) {
return ((Collection) parameters).size();
} else if (parameters instanceof Iterable) {
return Iterables.size((Iterable) parameters);
} else if (parameters instanceof Object[]) {
return ((Object[]) parameters).length;
}
}
LOG.warn("Unable to determine parameters size. Returning the default of 1.");
return 1;
}
private boolean hasSuitableRunnner(final Class<?> clazz) {
final RunWith runWith = clazz.getAnnotation(RunWith.class);
if (runWith != null) {
return (runWith.value().equals(Suite.class));
}
return false;
}
private static boolean isTestClass(Class<?> initialClazz) {
Class<?> clazz = initialClazz;
do {
if (clazz.isAnnotationPresent(RunWith.class)) {
logger.atFiner().log("Filtered out %s: is a Test class", initialClazz);
return true;
}
clazz = clazz.getEnclosingClass();
} while (clazz != null);
return false;
}
@TestOnly
public static boolean isJUnit4TestClass(final Class aClass) {
final int modifiers = aClass.getModifiers();
if ((modifiers & Modifier.ABSTRACT) != 0) return false;
if ((modifiers & Modifier.PUBLIC) == 0) return false;
if (aClass.getAnnotation(RunWith.class) != null) return true;
for (Method method : aClass.getMethods()) {
if (method.getAnnotation(Test.class) != null) return true;
}
return false;
}
private static boolean isJunit4Test(Class<?> container) {
return container.isAnnotationPresent(RunWith.class);
}
/**
* Classes that have a {@code RunWith} annotation for {@link Suite} or are automatically excluded
* to avoid picking up the suite class itself.
*/
private static boolean isSuite(Class<?> container) {
RunWith runWith = container.getAnnotation(RunWith.class);
return (runWith != null) && ((runWith.value() == CustomSuite.class));
}
@Test
public void testClassWithPersistenceContextWithWithOverwrittenConfiguration() throws Exception {
// GIVEN
final JCodeModel jCodeModel = new JCodeModel();
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
jAnnotationUse.param("value", JpaUnitRunner.class);
final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class);
jAnnotation.param("unitName", "test-unit-1");
final JAnnotationArrayMember propArray = jAnnotation.paramArray("properties");
propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.url").param("value",
"jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.driver").param("value", "org.h2.Driver");
propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.password").param("value", "test");
propArray.annotate(PersistenceProperty.class).param("name", "javax.persistence.jdbc.user").param("value", "test");
final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
jMethod.annotate(Test.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
final JpaUnitRunner runner = new JpaUnitRunner(cut);
final RunListener listener = mock(RunListener.class);
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
// WHEN
runner.run(notifier);
// THEN
final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
verify(listener).testStarted(descriptionCaptor.capture());
assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
verify(listener).testFinished(descriptionCaptor.capture());
assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
private boolean acceptRunWithClass(Class<?> clazz) {
return clazz.isAnnotationPresent(RunWith.class);
}