Java Code Examples for org.junit.runner.Description#getTestClass()

The following examples show how to use org.junit.runner.Description#getTestClass() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EJBContainerRule.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    if (test == null) {
        startingStatement = new StartingStatement(base, description.getTestClass());
    } else {
        startingStatement = new StartingStatement(new Statement() {
            @Override
            // this class avoids a dependency loop issue, we have it actually but that's just to make a nicer API
            public void evaluate() throws Throwable {
                // don't use testClass since it can be another instance that the test one
                new InjectStatement(base, test.getClass(), test, startingStatement).evaluate();
            }
        }, description.getTestClass());
    }
    return new ShutingDownStatement(startingStatement, startingStatement);
}
 
Example 2
Source File: DmnEngineTestRule.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected String expandResourcePath(Description description, String resourcePath) {
  if (resourcePath.contains("/")) {
    // already expanded path
    return resourcePath;
  }
  else {
    Class<?> testClass = description.getTestClass();
    if (resourcePath.isEmpty()) {
      // use test class and method name as resource file name
      return testClass.getName().replace(".", "/") + "." + description.getMethodName() + "." + DMN_SUFFIX;
    }
    else {
      // use test class location as resource location
      return testClass.getPackage().getName().replace(".", "/") + "/" + resourcePath;
    }
  }
}
 
Example 3
Source File: MemoryLeakDetectionRule.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, Description description) {
    Class<?> testClass = description.getTestClass();
    final List<Field> allocators = new ArrayList<Field>();
    for (Field field : testClass.getDeclaredFields()) {
        DetectLeak detectLeak = field.getAnnotation(DetectLeak.class);
        if (detectLeak == null) {
            continue;
        }
        if (!PooledByteBufAllocator.class.equals(field.getType())) {
            continue;
        }
        field.setAccessible(true);
        allocators.add(field);
    }
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            setupPools(allocators);
            base.evaluate();
            checkLeaks(allocators);
        }
    };
}
 
Example 4
Source File: ScottReportingRule.java    From scott with MIT License 6 votes vote down vote up
public Statement apply(final Statement base, final Description description) {
	return new Statement() {
		@Override
		public void evaluate() throws Throwable {
			String testClassName = description.getTestClass() != null ? description.getTestClass().getTypeName() : null;
			String testMethodName = description.getMethodName();
			
			/*
			 * Evaluate test and in case of a failure 
			 * throw a new error with the correct exception type
			 * that contains Scott's output and the original cause.
			 */
			try {
				base.evaluate();
			} catch (AssertionError assertionError) {
				throw new AssertionError(FailureRenderer.render(testClassName, testMethodName, assertionError), assertionError);
			} catch (Error error) {
				throw new Error(FailureRenderer.render(testClassName, testMethodName, error), error);
			} catch (Throwable throwable) {
				throw new Throwable(FailureRenderer.render(testClassName, testMethodName, throwable), throwable);
			}
		}
	};
}
 
Example 5
Source File: DmnEngineTestRule.java    From camunda-engine-dmn with Apache License 2.0 6 votes vote down vote up
protected String expandResourcePath(Description description, String resourcePath) {
  if (resourcePath.contains("/")) {
    // already expanded path
    return resourcePath;
  }
  else {
    Class<?> testClass = description.getTestClass();
    if (resourcePath.isEmpty()) {
      // use test class and method name as resource file name
      return testClass.getName().replace(".", "/") + "." + description.getMethodName() + "." + DMN_SUFFIX;
    }
    else {
      // use test class location as resource location
      return testClass.getPackage().getName().replace(".", "/") + "/" + resourcePath;
    }
  }
}
 
Example 6
Source File: AbstractGremlinSuite.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public boolean shouldRun(final Description description) {
    // first check if all tests from a class should be ignored - where "OptOut.method" is set to "*". the
    // description appears to be null in some cases of parameterized tests, but if the entire test case
    // was ignored it would have been caught earlier and these parameterized tests wouldn't be considered
    // for a call to shouldRun
    if (description.getTestClass() != null) {
        final boolean ignoreWholeTestCase = entireTestCaseToIgnore.stream().map(this::transformToClass)
                .anyMatch(claxx -> claxx.isAssignableFrom(description.getTestClass()));
        if (ignoreWholeTestCase) return false;
    }

    if (description.isTest()) {
        // next check if there is a test group to consider. if not then check for a  specific test to ignore
        return !(!testGroupToIgnore.isEmpty() && testGroupToIgnore.stream().anyMatch(optOut -> optOut.getTestClass().isAssignableFrom(description.getTestClass()) && description.getMethodName().equals(optOut.getMethodName())))
                && !individualSpecificTestsToIgnore.contains(description);
    }

    // explicitly check if any children want to run
    for (Description each : description.getChildren()) {
        if (shouldRun(each)) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: Fixture.java    From openCypher with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply( Statement base, Description description )
{
    return new Statement()
    {
        @Override
        public void evaluate() throws Throwable
        {
            testClass = description.getTestClass();
            testName = description.getMethodName();
            try
            {
                base.evaluate();
            }
            finally
            {
                testClass = null;
                testName = null;
            }
        }
    };
}
 
Example 8
Source File: KurentoTestListener.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public void testRunStarted(Description description) {
  testClass = description.getTestClass();

  log.debug("Starting test class {}", testClass.getName());
  invokeServices(ServiceMethod.START, TESTCLASS);
}
 
Example 9
Source File: ConditionalIgnoreRule.java    From androidTestRules with Apache License 2.0 5 votes vote down vote up
private boolean shouldIgnoreClass(Description description) {
    Class<?> clazz = description.getTestClass();
    do {
        if (shouldIgnoreAnnotatedElement(clazz)) {
            return true;
        }
    } while ((clazz = clazz.getSuperclass()) != null);

    return false;
}
 
Example 10
Source File: JUnitBenchmarkProvider.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {
    Class<?> clazz = description.getTestClass();
    String mname = description.getMethodName();
    Collection<Annotation> annotations = description.getAnnotations();
    final int rounds = getRoundsForFullMethodName(clazz.getCanonicalName() + "." + mname);

    List<Annotation> modifiedAnnotations = new ArrayList<Annotation>(annotations.size());

    boolean hit = false;

    for (Annotation a : annotations) {
        if (a.annotationType().equals(BenchmarkOptions.class)) {
            final BenchmarkOptions old = (BenchmarkOptions)a;
            BenchmarkOptions replacement = getWrappedBenchmarkOptions(old, rounds);
            modifiedAnnotations.add(replacement);
            log.debug("Modified BenchmarkOptions annotation on {}", mname);
            hit = true;
        } else {
            modifiedAnnotations.add(a);
            log.debug("Kept annotation {} with annotation type {} on {}",
                    new Object[] { a, a.annotationType(), mname });
        }
    }

    if (!hit) {
        BenchmarkOptions opts = getDefaultBenchmarkOptions(rounds);
        modifiedAnnotations.add(opts);
        log.debug("Added BenchmarkOptions {} with annotation type {} to {}",
                new Object[] { opts, opts.annotationType(), mname });
    }

    Description roundsAdjustedDesc =
            Description.createTestDescription(
                    clazz, mname,
                    modifiedAnnotations.toArray(new Annotation[modifiedAnnotations.size()]));
    return rule.apply(base, roundsAdjustedDesc);
}
 
Example 11
Source File: ParseDmnModelRule.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected void starting(Description description) {

  DmnModelResource dmnModelResource = description.getAnnotation(DmnModelResource.class);

  if(dmnModelResource != null) {

    String resourcePath = dmnModelResource.resource();

    if (resourcePath.isEmpty()) {
      Class<?> testClass = description.getTestClass();
      String methodName = description.getMethodName();

      String resourceFolderName = testClass.getName().replaceAll("\\.", "/");
      resourcePath = resourceFolderName + "." + methodName + ".dmn";
    }

    InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    try {
      dmnModelInstance = Dmn.readModelFromStream(resourceAsStream);
    } finally {
      IoUtil.closeSilently(resourceAsStream);
    }

  }

}
 
Example 12
Source File: TestSize.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if the test class in the {@link Description} is annotated with the test size
 *     annotation.
 */
public boolean testClassIsAnnotatedWithTestSize(Description description) {
  final Class<?> testClass = description.getTestClass();
  if (null == testClass) {
    return false;
  }

  if (hasAnnotation(testClass, runnerFilterAnnotationClass)
      || hasAnnotation(testClass, platformAnnotationClass)) {
    // If the test class is annotated with a test size annotation include it.
    return true;
  }
  return false;
}
 
Example 13
Source File: BugTestAwareRule.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Statement apply(final Statement base, final Description description) {
  BugTest bugTestAnnotation = description.getAnnotation(BugTest.class);
  if (bugTestAnnotation == null && description.getTestClass() != null) {
    bugTestAnnotation = description.getTestClass().getAnnotation(BugTest.class);
  }
  if (bugTestAnnotation != null && bugTestAnnotation.unresolved()) {
    return StatementFactory.createResultInvertingStatement(ERROR_TEST_MUST_FAIL, base, description);

  } else {
    return base;
  }
}
 
Example 14
Source File: TestPipeline.java    From beam with Apache License 2.0 5 votes vote down vote up
/** Returns the class + method name of the test. */
private String getAppName(Description description) {
  String methodName = description.getMethodName();
  Class<?> testClass = description.getTestClass();
  if (testClass.isMemberClass()) {
    return String.format(
        "%s$%s-%s",
        testClass.getEnclosingClass().getSimpleName(), testClass.getSimpleName(), methodName);
  } else {
    return String.format("%s-%s", testClass.getSimpleName(), methodName);
  }
}
 
Example 15
Source File: TestRuleStoreClassName.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the test class currently executing in this rule.
 */
public Class<?> getTestClass() {
  Description localDescription = description;
  if (localDescription == null) {
    throw new RuntimeException("The rule is not currently executing.");
  }
  return localDescription.getTestClass();
}
 
Example 16
Source File: AllureRunListener.java    From allure1 with Apache License 2.0 5 votes vote down vote up
public String getSuiteUid(Description description) {
    String suiteName = description.getClassName();
    if (!getSuites().containsKey(suiteName)) {
        Class testClass = description.getTestClass();
        Description suiteDescription;
        if (testClass != null) {
            suiteDescription = Description.createSuiteDescription(testClass);
        } else {
            suiteDescription = Description.createSuiteDescription(description.getClassName());
        }
        testSuiteStarted(suiteDescription);
    }
    return getSuites().get(suiteName);
}
 
Example 17
Source File: TestRequestBuilder.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean evaluateTest(Description description) {
  final Class<?> testClass = description.getTestClass();
  if ((testClass != null && testClass.isAnnotationPresent(annotationClass))
      || (description.getAnnotation(annotationClass) != null)) {
    return false;
  }
  return true;
}
 
Example 18
Source File: ServiceTalkTestTimeout.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {
    // Check if multiple Timeout are present and annotated with @Rule.
    Class<?> clazz = description.getTestClass();
    List<Class<?>> timeoutRuleClasses = new ArrayList<>(2);
    do {
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Rule.class) && Timeout.class.isAssignableFrom(field.getType())) {
                timeoutRuleClasses.add(clazz);
            }
        }
    } while ((clazz = clazz.getSuperclass()) != Object.class);
    if (timeoutRuleClasses.size() > 1) {
        StringBuilder sb = new StringBuilder(256)
                .append("Only one @Rule for a Timeout is allowed, but ")
                .append(timeoutRuleClasses.size())
                .append(" were detected in types: ");
        for (Class<?> clazz2 : timeoutRuleClasses) {
            sb.append(clazz2.getName()).append(", ");
        }
        sb.setLength(sb.length() - 2);
        throw new IllegalStateException(sb.toString());
    }
    // If timeout is specified in @Test, let that have precedence over the global timeout.
    Test testAnnotation = description.getAnnotation(Test.class);
    if (testAnnotation != null) {
        long timeout = testAnnotation.timeout();
        if (timeout > 0) {
            return new TimeoutStatement(base, timeout, TimeUnit.MILLISECONDS, onTimeout);
        }
    }
    return new TimeoutStatement(base, getTimeout(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS, onTimeout);
}
 
Example 19
Source File: SpringClassRule.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Apply <em>class-level</em> features of the <em>Spring TestContext
 * Framework</em> to the supplied {@code base} statement.
 * <p>Specifically, this method retrieves the {@link TestContextManager}
 * used by this rule and its associated {@link SpringMethodRule} and
 * invokes the {@link TestContextManager#beforeTestClass() beforeTestClass()}
 * and {@link TestContextManager#afterTestClass() afterTestClass()} methods
 * on the {@code TestContextManager}.
 * <p>In addition, this method checks whether the test is enabled in
 * the current execution environment. This prevents classes with a
 * non-matching {@code @IfProfileValue} annotation from running altogether,
 * even skipping the execution of {@code beforeTestClass()} methods
 * in {@code TestExecutionListeners}.
 * @param base the base {@code Statement} that this rule should be applied to
 * @param description a {@code Description} of the current test execution
 * @return a statement that wraps the supplied {@code base} with class-level
 * features of the Spring TestContext Framework
 * @see #getTestContextManager
 * @see #withBeforeTestClassCallbacks
 * @see #withAfterTestClassCallbacks
 * @see #withProfileValueCheck
 * @see #withTestContextManagerCacheEviction
 */
@Override
public Statement apply(Statement base, Description description) {
	Class<?> testClass = description.getTestClass();
	if (logger.isDebugEnabled()) {
		logger.debug("Applying SpringClassRule to test class [" + testClass.getName() + "]");
	}
	validateSpringMethodRuleConfiguration(testClass);
	TestContextManager testContextManager = getTestContextManager(testClass);

	Statement statement = base;
	statement = withBeforeTestClassCallbacks(statement, testContextManager);
	statement = withAfterTestClassCallbacks(statement, testContextManager);
	statement = withProfileValueCheck(statement, testClass);
	statement = withTestContextManagerCacheEviction(statement, testClass);
	return statement;
}
 
Example 20
Source File: AtsJunitTestListener.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @see org.junit.runner.notification.RunListener#testStarted(org.junit.runner.Description)
 */
@Override
public void testStarted( Description description ) throws Exception {
    
    if (!ActiveDbAppender.isAttached) {
        return;
    }

    if (log.isDebugEnabled()) {

        log.debug("testStarted(): Called when an atomic test is about to be started. Description generally class and method: "
                  + description); //, new Exception( "debugging trace" ) );

    }
    lastStartedMethodIsFailing = false;
    Class<?> testClass = description.getTestClass(); //testResult.getTestClass().getRealClass();

    String suiteName;
    String suiteSimpleName;
    String tcName = getTestName(description);
    // Update last started method. Note that testStarted() is invoked even before @Before methods
    lastStartedMethod = description.getMethodName(); // TODO: check for overridden methods
    String tcDescription = getTestDescription(description);

    suiteName = testClass.getName(); // assuming not JUnit 3 class "TestSuite"
    suiteSimpleName = testClass.getSimpleName();

    // check if we need to start a new group
    if (!suiteName.equals(lastSuiteName)) {
        if (lastSuiteName != null) {
            logger.endSuite();
        }

        String packName = suiteName.substring(0, suiteName.lastIndexOf('.'));
        logger.startSuite(packName, suiteSimpleName);
        lastSuiteName = suiteName;
    }

    // start a scenario and test case
    logger.startTestcase(suiteName, suiteSimpleName, tcName, "", tcDescription);

    // send TestStart event to all ATS agents
    TestcaseStateEventsDispacher.getInstance().onTestStart();

    logger.info("[JUnit]: Starting " + suiteName + "@" + tcName);
    super.testStarted(description);
}