下面列出了怎么用org.junit.platform.engine.UniqueId的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @return A formatted display name on success, {@code NULL} if the given
* identifier should be ignored.
*/
private String toName(TestIdentifier identifier) {
String name = identifier.getDisplayName();
List<Segment> segments = UniqueId.parse(identifier.getUniqueId()).getSegments();
if (!segments.isEmpty()) {
Segment lastSegment = segments.get(segments.size() - 1);
name = VINTAGE_ENGINE.equals(testEngine)
? toVintageName(identifier, lastSegment)
: toName(lastSegment);
}
return name;
}
/**
* Creates a task name for the specified {@code identifier}.
*
* @param testSuite The name of the test suite.
* @param identifier The test identifier.
* @return A task name representing the given identifier.
*/
static TaskName of(String testSuite, TestIdentifier identifier) {
TaskName result = new TaskName();
result.fullyQualifiedName = testSuite;
TestSource testSource = identifier.getSource().orElse(null);
if (testSource instanceof ClassSource) {
ClassSource classSource = (ClassSource)testSource;
result.nestedSuiteId = nestedSuiteId(testSuite, classSource.getClassName());
}
if (testSource instanceof MethodSource) {
MethodSource methodSource = (MethodSource)testSource;
result.nestedSuiteId = nestedSuiteId(testSuite, methodSource.getClassName());
result.invocation = invocation(UniqueId.parse(identifier.getUniqueId()));
result.testName = testName(methodSource.getMethodName(),
methodSource.getMethodParameterTypes());
}
return result;
}
/**
*
* @param id The unique test identifier.
* @return A string representation of the current invocation (might be {@code null}).
*/
static String invocation(UniqueId id) {
List<UniqueId.Segment> segments = id.getSegments();
if (!segments.isEmpty()) {
UniqueId.Segment last = segments.get(segments.size() - 1);
switch (last.getType()) {
case "dynamic-test":
case "test-template-invocation":
return last.getValue().replace("#", "");
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public FilterResult apply(TestDescriptor object) {
final UniqueId id = object.getUniqueId();
return alreadyTestedIds.computeIfAbsent(id, key -> {
final Optional<String> testName = toTestName(object);
final FilterResult result = testName.map(this::findMatchingResult)
.orElse(included("Not a leaf descriptor"));
if (result.excluded()) {
final String reason = result.getReason().orElse("");
eventDispatcher.executionFiltered(object, reason);
}
return result;
});
}
void verifyViolation(UniqueId testId, String messagePart) {
verifyStarted(testId);
FinishedTest test = finishedTests.stream().filter(result -> result.hasId(testId)).collect(onlyElement());
assertThat(test.result.getStatus())
.as("Test status of " + test)
.isEqualTo(FAILED);
assertThat(test.result.getThrowable().isPresent())
.as("Test has thrown Throwable: " + test)
.isTrue();
assertThat(test.result.getThrowable().get())
.as("Test Throwable of " + test)
.isInstanceOf(AssertionError.class);
assertThat(test.result.getThrowable().get().getMessage())
.as("AssertionError message of " + test)
.containsSequence(messagePart);
}
@Test
void an_unique_id() {
UniqueId ruleIdToDiscover = simpleRulesId(engineId)
.append(FIELD_SEGMENT_TYPE, SimpleRules.SIMPLE_RULE_FIELD_ONE_NAME);
EngineDiscoveryTestRequest discoveryRequest = new EngineDiscoveryTestRequest().withUniqueId(ruleIdToDiscover);
TestDescriptor descriptor = getOnlyTest(testEngine.discover(discoveryRequest, engineId));
assertThat(descriptor.getUniqueId()).isEqualTo(ruleIdToDiscover);
assertThat(descriptor.getDisplayName()).isEqualTo(SimpleRules.SIMPLE_RULE_FIELD_ONE_NAME);
assertThat(descriptor.getChildren()).isEmpty();
assertThat(descriptor.getDescendants()).isEmpty();
assertThat(descriptor.getType()).isEqualTo(TEST);
assertThat(descriptor.getSource().get()).isEqualTo(FieldSource.from(field(SimpleRules.class, SimpleRules.SIMPLE_RULE_FIELD_ONE_NAME)));
assertThat(descriptor.getParent().get().getSource().get()).isEqualTo(ClassSource.from(SimpleRules.class));
}
@Test
void no_redundant_descriptors() {
UniqueId redundantId = simpleRulesId(engineId)
.append(FIELD_SEGMENT_TYPE, SimpleRules.SIMPLE_RULE_FIELD_ONE_NAME);
EngineDiscoveryTestRequest discoveryRequest = new EngineDiscoveryTestRequest()
.withClass(SimpleRules.class)
.withUniqueId(redundantId);
TestDescriptor rootDescriptor = testEngine.discover(discoveryRequest, engineId);
TestDescriptor test = getOnlyElement(rootDescriptor.getChildren());
assertThat(test.getChildren()).as("all children of test").hasSize(4);
List<TestDescriptor> descriptorsWithSpecifiedId = test.getChildren().stream()
.filter(descriptor -> descriptor.getUniqueId().equals(redundantId))
.collect(toList());
assertThat(descriptorsWithSpecifiedId)
.as("descriptors with id " + redundantId)
.hasSize(1);
}
@Test
void no_redundant_library_descriptors() {
UniqueId simpleRulesId = simpleRulesInLibraryId(engineId);
UniqueId ruleIdOne = simpleRulesId.append(FIELD_SEGMENT_TYPE, SimpleRules.SIMPLE_RULE_FIELD_ONE_NAME);
UniqueId ruleIdTwo = simpleRulesId.append(FIELD_SEGMENT_TYPE, SimpleRules.SIMPLE_RULE_FIELD_TWO_NAME);
EngineDiscoveryTestRequest discoveryRequest = new EngineDiscoveryTestRequest()
.withUniqueId(ruleIdOne)
.withUniqueId(ruleIdTwo);
TestDescriptor rootDescriptor = testEngine.discover(discoveryRequest, engineId);
TestDescriptor simpleRules = getArchRulesDescriptorsOfOnlyChild(rootDescriptor).collect(onlyElement());
assertThat(toUniqueIds(simpleRules))
.as("ids of requested children of " + SimpleRules.class.getSimpleName())
.containsOnly(ruleIdOne, ruleIdTwo);
}
@Test
void mixed_class_methods_and_fields() {
EngineDiscoveryTestRequest discoveryRequest = new EngineDiscoveryTestRequest()
.withField(SimpleRuleField.class, SimpleRuleField.SIMPLE_RULE_FIELD_NAME)
.withMethod(SimpleRuleMethod.class, SimpleRuleMethod.SIMPLE_RULE_METHOD_NAME)
.withClass(SimpleRules.class);
TestDescriptor rootDescriptor = testEngine.discover(discoveryRequest, engineId);
Set<UniqueId> expectedLeafIds = new HashSet<>();
expectedLeafIds.add(simpleRuleFieldTestId(engineId));
expectedLeafIds.add(simpleRuleMethodTestId(engineId));
Stream.concat(
SimpleRules.RULE_FIELD_NAMES.stream().map(fieldName ->
simpleRulesId(engineId).append(FIELD_SEGMENT_TYPE, fieldName)),
SimpleRules.RULE_METHOD_NAMES.stream().map(methodName ->
simpleRulesId(engineId).append(METHOD_SEGMENT_TYPE, methodName)))
.forEach(expectedLeafIds::add);
assertThat(getAllLeafUniqueIds(rootDescriptor))
.as("children discovered by mixed selectors")
.containsOnlyElementsOf(expectedLeafIds);
}
@Test
void mixed_rules_by_unique_id_and_class_with_violation() {
UniqueId fieldRuleInLibrary = simpleRulesInLibraryId(engineId)
.append(FIELD_SEGMENT_TYPE, SimpleRules.SIMPLE_RULE_FIELD_ONE_NAME);
UniqueId methodRuleInLibrary = simpleRulesInLibraryId(engineId)
.append(METHOD_SEGMENT_TYPE, SimpleRules.SIMPLE_RULE_METHOD_ONE_NAME);
simulateCachedClassesForTest(SimpleRuleLibrary.class, UnwantedClass.CLASS_VIOLATING_RULES);
simulateCachedClassesForTest(SimpleRuleField.class, UnwantedClass.CLASS_VIOLATING_RULES);
EngineExecutionTestListener testListener = execute(engineId, new EngineDiscoveryTestRequest()
.withClass(SimpleRuleField.class)
.withUniqueId(fieldRuleInLibrary)
.withUniqueId(methodRuleInLibrary));
testListener.verifyViolation(simpleRuleFieldTestId(engineId), UnwantedClass.CLASS_VIOLATING_RULES.getSimpleName());
testListener.verifyViolation(fieldRuleInLibrary, UnwantedClass.CLASS_VIOLATING_RULES.getSimpleName());
testListener.verifyViolation(methodRuleInLibrary, UnwantedClass.CLASS_VIOLATING_RULES.getSimpleName());
}
@Test
void library_sub_rules() {
simulateCachedClassesForTest(IgnoredLibrary.class, UnwantedClass.CLASS_VIOLATING_RULES);
EngineExecutionTestListener testListener = execute(engineId, IgnoredLibrary.class);
UniqueId classWithIgnoredMethod = engineId
.append(CLASS_SEGMENT_TYPE, IgnoredLibrary.class.getName())
.append(FIELD_SEGMENT_TYPE, IgnoredLibrary.UNIGNORED_LIB_TWO_FIELD)
.append(CLASS_SEGMENT_TYPE, IgnoredMethod.class.getName());
testListener.verifySkipped(classWithIgnoredMethod
.append(METHOD_SEGMENT_TYPE, IgnoredMethod.IGNORED_RULE_METHOD));
testListener.verifyViolation(classWithIgnoredMethod
.append(METHOD_SEGMENT_TYPE, IgnoredMethod.UNIGNORED_RULE_METHOD));
}
@Test
void library_sub_rules() {
simulateCachedClassesForTest(MetaIgnoredLibrary.class, UnwantedClass.CLASS_VIOLATING_RULES);
EngineExecutionTestListener testListener = execute(engineId, MetaIgnoredLibrary.class);
UniqueId classWithIgnoredMethod = engineId
.append(CLASS_SEGMENT_TYPE, MetaIgnoredLibrary.class.getName())
.append(FIELD_SEGMENT_TYPE, MetaIgnoredLibrary.UNIGNORED_LIB_TWO_FIELD)
.append(CLASS_SEGMENT_TYPE, MetaIgnoredMethod.class.getName());
testListener.verifySkipped(classWithIgnoredMethod
.append(METHOD_SEGMENT_TYPE, MetaIgnoredMethod.IGNORED_RULE_METHOD));
testListener.verifyViolation(classWithIgnoredMethod
.append(METHOD_SEGMENT_TYPE, MetaIgnoredMethod.UNIGNORED_RULE_METHOD));
}
public static void execute(Class<?> testClass) throws Exception {
try {
JupiterTestEngine engine = new JupiterTestEngine();
TestClassEngineDiscoveryRequest discoveryRequest = new TestClassEngineDiscoveryRequest(testClass);
TestDescriptor testDescriptor = engine.discover(discoveryRequest, UniqueId.forEngine("foo-bar"));
EngineExecutionListener listener = new NoOpEngineExecutionListener();
ConfigurationParameters parameters = new NoConfigurationParameters();
engine.execute(new ExecutionRequest(testDescriptor, listener, parameters));
} catch (UndeclaredThrowableException e) {
Throwable cause = getFirstNonUndeclaredThrowableCause(e);
if (cause instanceof Error) {
throw ( Error ) cause;
} else if (cause instanceof RuntimeException) {
throw ( RuntimeException ) cause;
} else if (cause instanceof Exception) {
throw ( Exception ) cause;
} else {
throw e;
}
}
}
@Override
public TestDescriptor discover(EngineDiscoveryRequest discoveryRequest,
UniqueId uniqueId) {
// Discover test(s) and return a TestDescriptor object
TestDescriptor testDescriptor = new EngineDescriptor(uniqueId,
"My test");
return testDescriptor;
}
@Override
public TestDescriptor discover(EngineDiscoveryRequest discoveryRequest,
UniqueId uniqueId) {
// Discover test(s) and return a TestDescriptor object
TestDescriptor testDescriptor = new EngineDescriptor(uniqueId,
"My test");
return testDescriptor;
}
/**
* @return The formatted test name using the configured color theme.
*/
public String format() {
final List<TestIdentifier> path = getPath(testPlan, identifier);
testEngine = UniqueId.parse(identifier.getUniqueId())
.getEngineId()
.orElse(null);
return path.stream()
.skip(1)
.map(this::toName)
.filter(Objects::nonNull)
.collect(Collectors.joining());
}
/**
* Converts the specified unique id to a test name
*
* @param id The unique identifier.
* @return The converted test name.
*/
String toTestName(UniqueId id) {
return id.getSegments().stream()
.skip(1)
.map(Segment::getValue)
.collect(Collectors.joining("."));
}
@Test
public void shouldFindDynamicTest() {
UniqueId id = UniqueId.root("method", "someTestMethod")
.append("dynamic-test", "#1");
String result = TaskName.invocation(id);
assertThat(result, equalTo("1"));
}
@Test
public void shouldFindTestTemplateInvocation() {
UniqueId id = UniqueId.root("method", "someTestMethod")
.append("test-template-invocation", "#1");
String result = TaskName.invocation(id);
assertThat(result, equalTo("1"));
}
@Test
public void shouldReturnNullOtherwise() {
UniqueId id = UniqueId.root("method", "someTestMethod");
String result = TaskName.invocation(id);
assertThat(result, nullValue());
}
@Test
@Ignore
public void shouldSkipEngineWhenConvertingUniqueIds() {
GlobFilter filter = newGlobFilter("");
filter.toTestName(UniqueId.parse(""));
}
@Override
public TestDescriptor discover(EngineDiscoveryRequest discoveryRequest, UniqueId uniqueId) {
ArchUnitEngineDescriptor result = new ArchUnitEngineDescriptor(uniqueId);
resolveRequestedClasspathRoot(discoveryRequest, uniqueId, result);
resolveRequestedPackages(discoveryRequest, uniqueId, result);
resolveRequestedClasses(discoveryRequest, uniqueId, result);
resolveRequestedMethods(discoveryRequest, uniqueId, result);
resolveRequestedFields(discoveryRequest, uniqueId, result);
resolveRequestedUniqueIds(discoveryRequest, uniqueId, result);
return result;
}
private void resolveRequestedClasspathRoot(EngineDiscoveryRequest discoveryRequest, UniqueId uniqueId, ArchUnitEngineDescriptor result) {
Stream<JavaClass> classes = discoveryRequest.getSelectorsByType(ClasspathRootSelector.class).stream()
.flatMap(this::getContainedClasses);
filterCandidatesAndLoadClasses(classes, discoveryRequest)
.forEach(clazz -> ArchUnitTestDescriptor.resolve(
result, ElementResolver.create(result, uniqueId, clazz), cache.get()));
}
private void resolveRequestedPackages(EngineDiscoveryRequest discoveryRequest, UniqueId uniqueId, ArchUnitEngineDescriptor result) {
String[] packages = discoveryRequest.getSelectorsByType(PackageSelector.class).stream()
.map(PackageSelector::getPackageName)
.toArray(String[]::new);
Stream<JavaClass> classes = getContainedClasses(packages);
filterCandidatesAndLoadClasses(classes, discoveryRequest)
.forEach(clazz -> ArchUnitTestDescriptor.resolve(
result, ElementResolver.create(result, uniqueId, clazz), cache.get()));
}
private void resolveRequestedClasses(EngineDiscoveryRequest discoveryRequest, UniqueId uniqueId, ArchUnitEngineDescriptor result) {
discoveryRequest.getSelectorsByType(ClassSelector.class).stream()
.map(ClassSelector::getJavaClass)
.filter(this::isArchUnitTestCandidate)
.forEach(clazz -> ArchUnitTestDescriptor.resolve(
result, ElementResolver.create(result, uniqueId, clazz), cache.get()));
}
ArchUnitMethodDescriptor(UniqueId uniqueId, Method method, Supplier<JavaClasses> classes) {
super(uniqueId.append("method", method.getName()), method.getName(), MethodSource.from(method), method);
validate(method);
this.method = method;
this.classes = classes;
this.method.setAccessible(true);
}
AbstractArchUnitTestDescriptor(UniqueId uniqueId, String displayName, TestSource source, AnnotatedElement... elements) {
super(uniqueId, displayName, source);
tags = Arrays.stream(elements).map(this::findTagsOn).flatMap(Collection::stream).collect(toSet());
skipResult = Arrays.stream(elements)
.map(e -> AnnotationSupport.findAnnotation(e, ArchIgnore.class))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.map(ignore -> SkipResult.skip(ignore.reason()))
.orElse(SkipResult.doNotSkip());
}
PossiblyResolvedClass resolveClass() {
UniqueId.Segment nextSegment = checkNotNull(segmentsToResolve.peekFirst());
if (!CLASS_SEGMENT_TYPE.equals(nextSegment.getType())) {
return new ClassNotRequested();
}
return tryResolveClass(classOf(nextSegment), processedId.append(nextSegment));
}
private PossiblyResolvedClass tryResolveClass(Class<?> clazz, UniqueId classId) {
ElementResolver childResolver = new ElementResolver(engineDescriptor, classId, tail(segmentsToResolve));
return engineDescriptor.findByUniqueId(classId)
.<PossiblyResolvedClass>map(testDescriptor ->
new RequestedAndSuccessfullyResolvedClass(testDescriptor, childResolver))
.orElseGet(() -> new RequestedButUnresolvedClass(clazz, childResolver));
}
@MayResolveTypesViaReflection(reason = "Within the ArchUnitTestEngine we may resolve types via reflection, since they are needed anyway")
private Class<?> classOf(UniqueId.Segment segment) {
try {
return Class.forName(segment.getValue());
} catch (ClassNotFoundException e) {
throw new ArchTestInitializationException(e, "Failed to load class from %s segment %s",
UniqueId.class.getSimpleName(), segment);
}
}