@Override protected Statement methodBlock(FrameworkMethod frameworkMethod) { Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); PortalClassLoaderUtil.setClassLoader(contextClassLoader); TestClass testClass = getTestClass(); List<FrameworkMethod> beforeFrameworkMethods = testClass.getAnnotatedMethods(Before.class); List<FrameworkMethod> afterFrameworkMethods = testClass.getAnnotatedMethods(After.class); List<String> arguments = createArguments(frameworkMethod); Class<?> clazz = testClass.getJavaClass(); return new RunInNewJVMStatment( _classPath, arguments, clazz, beforeFrameworkMethods, frameworkMethod, afterFrameworkMethods); }
/** @see Parameterized */ private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception { List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Parameterized.Parameters.class); for (FrameworkMethod each : methods) { int modifiers = each.getMethod().getModifiers(); if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) return each; } throw new Exception("No public static parameters method on class " + testClass.getName()); }
@Test public void annotatedMethodValues() { TestClass tc = new TestClass(MethodsAnnotated.class); List<String> values = tc.getAnnotatedMethodValues(new MethodsAnnotated(), Ignore.class, String.class); assertThat(values, hasItem("jupiter")); assertThat(values.size(), is(1)); }
@Test public void annotatedFieldValues() { TestClass tc = new TestClass(FieldAnnotated.class); List<String> values = tc.getAnnotatedFieldValues(new FieldAnnotated(), Rule.class, String.class); assertThat(values, hasItem("andromeda")); assertThat(values.size(), is(1)); }
private boolean shouldInitMockitoMocks() { TestClass testClass = this.getTestClass(); InitMocks initMocks = testClass.getAnnotation(InitMocks.class); if (initMocks != null) { return initMocks.value(); } return true; }
@Test public void providesAnnotatedFieldsSortedByName() { TestClass tc = new TestClass(FieldAnnotated.class); List<FrameworkField> annotatedFields = tc.getAnnotatedFields(); assertThat("Wrong number of annotated fields.", annotatedFields.size(), is(3)); assertThat( "First annotated field is wrong.", annotatedFields.iterator().next().getName(), is("fieldA")); }
/** * 判断是否需要执行MilouDbUnitTestExecutionListener * * @param testClass */ private void switchMilouDBUnitTestExecutionListener(TestClass testClass) { List<FrameworkMethod> DBSituations = testClass.getAnnotatedMethods(DBSituations.class); List<FrameworkMethod> DBSetupSituation = testClass.getAnnotatedMethods(DBSetupSituation.class); List<FrameworkMethod> DBTeardownSituation = testClass.getAnnotatedMethods(DBTeardownSituation.class); if (!CollectionUtils.isEmpty(DBSituations) || !CollectionUtils.isEmpty(DBSetupSituation) || !CollectionUtils.isEmpty(DBTeardownSituation)) { MilouDBThreadLocal.setMilouDBListener(Boolean.valueOf(true)); } }
public InternalRemoteRunner( Class<?> testClass, String endpoint, Class<? extends Runner> remoteRunnerClass) throws InitializationError { super(testClass); this.testClass = testClass; this.remoteRunnerClass = remoteRunnerClass; TestClass tc = new TestClass(testClass); description = Description.createTestDescription(testClass, tc.getName(), tc.getAnnotations()); for (FrameworkMethod method : tc.getAnnotatedMethods(Test.class)) { String methodName = method.getName(); Description child = Description.createTestDescription(testClass, methodName, method.getAnnotations()); methodNames.put(child, methodName); description.addChild(child); } if (executorService == null) { String ep = System.getProperty("junit.remote.endpoint"); if (ep == null) { ep = endpoint; } for (String e : ep.split(",")) { if (e.trim().equals("")) { continue; } endpoints.add(e.trim()); } executorService = Executors.newFixedThreadPool(endpoints.size()); } setScheduler( new RunnerScheduler() { @Override public void schedule(final Runnable childStatement) { SEMAPHORE.reducePermits(1); executorService.submit(new SemaphoreDelegate(childStatement)); } @Override public void finished() { try { SEMAPHORE.acquire(); SEMAPHORE.release(); } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } } }); }
public int getMaxTestNameLen() { if (0 == maxMethodNameLen) { int ml = 0; final TestClass tc = new TestClass(getClass()); final List<FrameworkMethod> testMethods = tc.getAnnotatedMethods(org.junit.Test.class); for (Iterator<FrameworkMethod> iter = testMethods.iterator(); iter.hasNext(); ) { final int l = iter.next().getName().length(); if (ml < l) { ml = l; } } maxMethodNameLen = ml; } return maxMethodNameLen; }
protected static List<MethodKey> getMethodKeys( Class<?> targetClass, Class<? extends Annotation> annotationClass) { TestClass testClass = new TestClass(targetClass); List<FrameworkMethod> frameworkMethods = testClass.getAnnotatedMethods(annotationClass); List<MethodKey> methodKeys = new ArrayList<MethodKey>(frameworkMethods.size()); for (FrameworkMethod annotatedFrameworkMethod : frameworkMethods) { methodKeys.add(new MethodKey(annotatedFrameworkMethod.getMethod())); } return methodKeys; }
@SuppressWarnings("deprecation") private void addSinglePointMethods(ParameterSignature sig, List<PotentialAssignment> list) { for (FrameworkMethod dataPointMethod : fClass.getAnnotatedMethods(DataPoint.class)) { Class<?> type = sig.getType(); if ((dataPointMethod.producesType(type))) list.add(new MethodParameterValue(dataPointMethod)); } }
@Test public void testFindDataProviderLocationShouldReturnTestClassContainingSetLocationInUseDataProviderAnnotation() { // Given: final Class<?> dataProviderLocation = DataProviderRunnerTest.class; doReturn(new Class<?>[] {dataProviderLocation}).when(useDataProvider).location(); // When: TestClass result = underTest.findDataProviderLocation(useDataProvider); // Then: assertThat(result).isNotNull(); // assertThat(result.getJavaClass()).isEqualTo(dataProviderLocation); assertThat(result.getName()).isEqualTo(dataProviderLocation.getName()); }
@Override public Description getDescription() { Description description = Description.createSuiteDescription(getName(), fTestClass.getAnnotations()); for (T child : getFilteredChildren()) description.addChild(describeChild(child)); return description; }
private List<Class<?>> gatherClasses() { ArrayList<Class<?>> result = new ArrayList<Class<?>>(); List<Classes> classeses = fTestClass.getAnnotatedFieldValues(fInstance, SuiteClasses2.class, Classes.class); for (Classes each : classeses) result.addAll(each.get()); return result; }
private static Object createTestObject(TestClass testClass) throws InitializationError { try { return testClass.getOnlyConstructor().newInstance(); } catch (Exception ex) { throw new InitializationError(ex); } }
public Suite2(Class<?> testClass) throws InitializationError { fTestClass = new TestClass(testClass); try { fInstance = fTestClass.getOnlyConstructor().newInstance(); } catch (Exception e) { throw new InitializationError(e); } }
private void addMultiPointMethods(List<PotentialAssignment> list) { for (FrameworkMethod dataPointsMethod : fClass.getAnnotatedMethods(DataPoints.class)) try { addArrayValues(dataPointsMethod.getName(), list, dataPointsMethod.invokeExplosively(null)); } catch (Throwable e) { // ignore and move on } }
private void setAllSituationIntoMap(TestClass testClass) { List<FrameworkMethod> frameworkMethods = testClass.getAnnotatedMethods(Test.class); for (FrameworkMethod method : frameworkMethods) { List<SituationInfo> list = getSituationInfos(method); if (!CollectionUtils.isEmpty(list)) { situationInfos.put(method, list); } } }
private List<S2TestRule> setS2ClassRule(S2TestRule... rules) { List<S2TestRule> ruleList = new ArrayList<S2TestRule>(); for (S2TestRule rule : rules) { ruleList.add(rule); } when(testClass.getAnnotatedFieldValues(null, ClassRule.class, S2TestRule.class)) .thenReturn(ruleList); return ruleList; }
private void handleInitializationError( final boolean developmentMode, final List<TestClassResult> result, final String klassName, final Class<?> klass, final InitializationError e) { TestClass testClass = new TestClass(klass); boolean allMethods = (!developmentMode) || (klass.getAnnotation(TestDuringDevelopment.class) != null); List<Throwable> causes = e.getCauses(); long now = System.currentTimeMillis(); List<TestCaseResult> testCaseResults = new ArrayList<TestCaseResult>(); List<FrameworkMethod> annotatedMethods = testClass.getAnnotatedMethods(Test.class); Exception wrapperException = new Exception("Error during initialization. See log for details"); wrapperException.setStackTrace(new StackTraceElement[0]); for (FrameworkMethod frameworkMethod : annotatedMethods) { if (allMethods || (frameworkMethod.getAnnotation(TestDuringDevelopment.class) != null)) { TestCaseResult testCaseResult = new TestCaseResult(frameworkMethod.getName(), now, now, wrapperException); testCaseResults.add(testCaseResult); } } TestClassResult classResult = new TestClassResult(klassName, 0, testCaseResults.size(), 0, 0, now, now, testCaseResults); result.add(classResult); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.write("Error during initialization of test class '" + klassName + "':\n"); for (Throwable throwable : causes) { throwable.printStackTrace(pw); } LOGGER.log(Level.SEVERE, sw.toString()); }
/** 完成Stub的元数据扫描,构建stub元数据仓库 */ private void stubInfoRepoInit(TestClass testClass) { // 加载本地stub仓库 List<FrameworkMethod> stubMethods = testClass.getAnnotatedMethods(Stub.class); if (!CollectionUtils.isEmpty(stubMethods)) { for (FrameworkMethod fm : stubMethods) { StubInfo info = new StubInfo(); String stubId = fm.getAnnotation(Stub.class).value(); info.setStubId(stubId); info.setStubClass(testClass.getJavaClass()); info.setStubMethod(fm.getMethod()); logger.info("[milou] scan stub,stubId={}", stubId); StubInfoRepo.setIntoStubInfoRepo(stubId, info); } } StubLocation locationAnno = testClass.getJavaClass().getAnnotation(StubLocation.class); if (locationAnno != null && !locationAnno.value().equals(StubLocation.LOCAL)) { // 根据注解加载指定路径下的stub仓库 List<Class<?>> scanList = PackageScanner.getStubClass(locationAnno.value()); StubInfoScanner.scanAllStubClass(scanList, StubInfoRepo.getStubInfoRepo()); } }
private List<TestCaseResult> createErrorTestCaseResults( final Class<?> klass, final boolean developmentMode, final long now) { TestClass testClass = new TestClass(klass); boolean allMethods = (!developmentMode) || (klass.getAnnotation(TestDuringDevelopment.class) != null); List<FrameworkMethod> annotatedMethods = testClass.getAnnotatedMethods(Test.class); List<TestCaseResult> result = new ArrayList<TestCaseResult>(); for (FrameworkMethod frameworkMethod : annotatedMethods) { if (allMethods || (frameworkMethod.getAnnotation(TestDuringDevelopment.class) != null)) { Exception exception = new Exception( "Service object behind the reference was null. We experienced this when the activate" + " method of a DS component threw an exception but there can be other causes. Please" + " check the log! Please note, that in Equinox sometimes such exceptions are" + " written only into different files in the configuration folder."); exception.setStackTrace(new StackTraceElement[0]); result.add(new TestCaseResult(frameworkMethod.getName(), now, now, exception)); } } return result; }
private void addFields(ParameterSignature sig, List<PotentialAssignment> list) { for (final Field field : fClass.getJavaClass().getFields()) { if (Modifier.isStatic(field.getModifiers())) { Class<?> type = field.getType(); if (sig.canAcceptArrayType(type) && field.getAnnotation(DataPoints.class) != null) { addArrayValues(field.getName(), list, getStaticFieldValue(field)); } else if (sig.canAcceptType(type) && field.getAnnotation(DataPoint.class) != null) { list.add(PotentialAssignment.forValue(field.getName(), getStaticFieldValue(field))); } } } }
/** {@inheritDoc} */ @Override public Object invokeExplosively(final Object target, final Object... params) throws Throwable { if (!parameters_.isEmpty()) { final List<FrameworkField> annotatedFieldsByParameter = testClass_.getAnnotatedFields(Parameter.class); if (annotatedFieldsByParameter.size() != parameters_.size()) { throw new Exception( "Wrong number of parameters and @Parameter fields." + " @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + parameters_.size() + "."); } for (final FrameworkField each : annotatedFieldsByParameter) { final Field field = each.getField(); final Parameter annotation = field.getAnnotation(Parameter.class); final int index = annotation.value(); try { field.set(target, parameters_.get(index)); } catch (final IllegalArgumentException iare) { throw new Exception( testClass_.getName() + ": Trying to set " + field.getName() + " with the value " + parameters_.get(index) + " that is not the right type (" + parameters_.get(index).getClass().getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare); } } } return super.invokeExplosively(target, params); }
private static Set<Field> getTestFactoryFields( TestClass testClass, TestSessionFactory.Scope scope) { Set<Field> testFactoryFields = new HashSet<Field>(); for (FrameworkField frameworkField : testClass.getAnnotatedFields(TestSessionFactory.class)) { Field field = frameworkField.getField(); if (scope == field.getAnnotation(TestSessionFactory.class).scope()) { field.setAccessible(true); testFactoryFields.add(field); } } return testFactoryFields; }
@Override protected Statement classBlock(final RunNotifier notifier) { TestClass testClass = getTestClass(); Method checkMethod = getMethod(testClass.getJavaClass(), CheckBefore.class); Exception exception = execute(newInstance(testClass.getJavaClass()), checkMethod); Statement statement; if (exception == null) { statement = super.classBlock(notifier); } else { LOG.warn( "skip test " + testClass.getJavaClass().getSimpleName() + " cause check faild: " + exception.getMessage()); return new Statement() { @Override public void evaluate() throws Throwable { Description description = Description.createSuiteDescription(getClass()); notifier.fireTestIgnored(description); } }; } return statement; }
public TestClassAttributes( TestClass testClass, ClassResolver classResolver, DependencyCollector dependencyCollector) { beforeMethods = testClass.getAnnotatedMethods(Before.class); afterMethods = testClass.getAnnotatedMethods(After.class); stjsClass = classResolver.resolve(testClass.getName()); htmlFixture = testClass.getJavaClass().getAnnotation(HTMLFixture.class); scripts = getScriptsPathes( testClass.getJavaClass(), Scripts.class, new Function1<Annotation, Collection<String>>() { @Override public Collection<String> $invoke(Annotation annotation) { return Arrays.asList(Scripts.class.cast(annotation).value()); } }); scriptsBefore = getScriptsPathes( testClass.getJavaClass(), ScriptsBefore.class, new Function1<Annotation, Collection<String>>() { @Override public Collection<String> $invoke(Annotation annotation) { return Arrays.asList(ScriptsBefore.class.cast(annotation).value()); } }); scriptsAfter = getScriptsPathes( testClass.getJavaClass(), ScriptsAfter.class, new Function1<Annotation, Collection<String>>() { @Override public Collection<String> $invoke(Annotation annotation) { return Arrays.asList(ScriptsAfter.class.cast(annotation).value()); } }); dependencies = dependencyCollector.orderAllDependencies(stjsClass); }
/** Returns a name used to describe this Runner */ protected String getName() { return fTestClass.getName(); }
/** @return list of {@link FrameworkField}s annotated with {@link Rule} */ protected List<FrameworkField> classRuleFields() { return fTestClass.getAnnotatedFields(ClassRule.class); }
/** * Returns a {@link Statement}: run all non-overridden {@code @AfterClass} methods on this class * and superclasses before executing {@code statement}; all AfterClass methods are always * executed: exceptions thrown by previous steps are combined, if necessary, with exceptions from * AfterClass methods into a {@link MultipleFailureException}. */ protected Statement withAfterClasses(Statement statement) { List<FrameworkMethod> afters = fTestClass.getAnnotatedMethods(AfterClass.class); return afters.isEmpty() ? statement : new RunAfters(statement, afters, null); }