下面列出了怎么用org.junit.jupiter.api.TestInstance的API类实例代码及写法,或者点击链接到github查看源代码。
protected void doFinally(ExtensionContext context, TestInstance.Lifecycle lifecycleForClean) {
FormEngine formEngine = getFormEngine(context);
FormEngineConfiguration formEngineConfiguration = formEngine.getFormEngineConfiguration();
try {
String annotationDeploymentKey = context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY;
String deploymentIdFromDeploymentAnnotation = getStore(context).get(annotationDeploymentKey, String.class);
if (deploymentIdFromDeploymentAnnotation != null) {
FormTestHelper.annotationDeploymentTearDown(formEngine, deploymentIdFromDeploymentAnnotation, context.getRequiredTestClass(),
context.getRequiredTestMethod().getName());
getStore(context).remove(annotationDeploymentKey);
}
AnnotationSupport.findAnnotation(context.getTestMethod(), CleanTest.class)
.ifPresent(cleanTest -> removeDeployments(formEngine.getFormRepositoryService()));
if (context.getTestInstanceLifecycle().orElse(TestInstance.Lifecycle.PER_METHOD) == lifecycleForClean) {
cleanTestAndAssertAndEnsureCleanDb(context, formEngine);
}
} finally {
formEngineConfiguration.getClock().reset();
}
}
@Override
public void afterEach(ExtensionContext context) {
FlowableEventTestHelper flowableTestHelper = getTestHelper(context);
EventRegistryEngine eventRegistryEngine = flowableTestHelper.getEventRegistryEngine();
String deploymentIdFromDeploymentAnnotation = flowableTestHelper.getDeploymentIdFromDeploymentAnnotation();
if (deploymentIdFromDeploymentAnnotation != null) {
EventTestHelper.annotationDeploymentTearDown(flowableTestHelper.getEventRepositoryService(),
deploymentIdFromDeploymentAnnotation, context.getRequiredTestClass(), context.getRequiredTestMethod().getName());
flowableTestHelper.setDeploymentIdFromDeploymentAnnotation(null);
}
try {
if (context.getTestInstanceLifecycle().orElse(TestInstance.Lifecycle.PER_METHOD) == TestInstance.Lifecycle.PER_METHOD) {
cleanTestAndAssertAndEnsureCleanDb(context, eventRegistryEngine);
}
} finally {
eventRegistryEngine.getEventRegistryEngineConfiguration().getClock().reset();
}
}
@Override
public void beforeAll(ExtensionContext extensionContext) throws Exception {
final Class<?> testClass = extensionContext.getRequiredTestClass();
final MicronautTest micronautTest = AnnotationSupport.findAnnotation(testClass, MicronautTest.class).orElse(null);
beforeClass(extensionContext, testClass, micronautTest);
getStore(extensionContext).put(ApplicationContext.class, applicationContext);
if (specDefinition != null) {
TestInstance ti = AnnotationSupport.findAnnotation(testClass, TestInstance.class).orElse(null);
if (ti != null && ti.value() == TestInstance.Lifecycle.PER_CLASS) {
Object testInstance = extensionContext.getRequiredTestInstance();
applicationContext.inject(testInstance);
}
}
beforeTestClass(buildContext(extensionContext));
}
private TestInstance.Lifecycle determineTestLifecycle(ExtensionContext ec) {
// check the test for import org.junit.jupiter.api.TestInstance annotation
TestInstance annotation = ec.getRequiredTestClass().getAnnotation(TestInstance.class);
if (annotation != null) {
return annotation.value();
} else {
return TestInstance.Lifecycle.PER_METHOD;
}
}
protected void doFinally(ExtensionContext context, TestInstance.Lifecycle lifecycleForClean) {
IdmEngine idmEngine = getIdmEngine(context);
IdmEngineConfiguration idmEngineConfiguration = idmEngine.getIdmEngineConfiguration();
try {
if (context.getTestInstanceLifecycle().orElse(TestInstance.Lifecycle.PER_METHOD) == lifecycleForClean) {
cleanTestAndAssertAndEnsureCleanDb(context, idmEngine);
}
} finally {
idmEngineConfiguration.getClock().reset();
}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
ProcessEngine processEngine = getProcessEngine(context);
// Always reset authenticated user to avoid any mistakes
processEngine.getIdentityService().setAuthenticatedUserId(null);
try {
AbstractFlowableTestCase.validateHistoryData(processEngine);
} finally {
doFinally(context, TestInstance.Lifecycle.PER_METHOD);
}
}
private void startWeldContainerIfAppropriate(TestInstance.Lifecycle expectedLifecycle, ExtensionContext context) throws Exception {
// is the lifecycle is what we expect it to be, start Weld container
if (determineTestLifecycle(context).equals(expectedLifecycle)) {
Object testInstance = context.getTestInstance().orElseGet(null);
if (testInstance == null) {
throw new IllegalStateException("ExtensionContext.getTestInstance() returned empty Optional!");
}
// store info about explicit param injection, either from global settings or from annotation on the test class
storeExplicitParamResolutionInformation(context);
// all found fields which are WeldInitiator and have @WeldSetup annotation
List<Field> foundInitiatorFields = new ArrayList<>();
WeldInitiator initiator = null;
// We will go through class hierarchy in search of @WeldSetup field (even private)
for (Class<?> clazz = testInstance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
// Find @WeldSetup field using getDeclaredFields() - this allows even for private fields
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(WeldSetup.class)) {
Object fieldInstance;
try {
fieldInstance = field.get(testInstance);
} catch (IllegalAccessException e) {
// In case we cannot get to the field, we need to set accessibility as well
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
field.setAccessible(true);
return null;
});
fieldInstance = field.get(testInstance);
}
if (fieldInstance != null && fieldInstance instanceof WeldInitiator) {
initiator = (WeldInitiator) fieldInstance;
foundInitiatorFields.add(field);
} else {
// Field with other type than WeldInitiator was annotated with @WeldSetup
throw new IllegalStateException("@WeldSetup annotation should only be used on a field of type"
+ " WeldInitiator but was found on a field of type " + field.getType() + " which is declared "
+ "in class " + field.getDeclaringClass());
}
}
}
}
// Multiple occurrences of @WeldSetup in the hierarchy will lead to an exception
if (foundInitiatorFields.size() > 1) {
throw new IllegalStateException(foundInitiatorFields.stream().map(f -> "Field type - " + f.getType() + " which is "
+ "in " + f.getDeclaringClass()).collect(Collectors.joining("\n", "Multiple @WeldSetup annotated fields found, "
+ "only one is allowed! Fields found:\n", "")));
}
// at this point we can be sure that either no or exactly one WeldInitiator was found
if (initiator == null) {
Weld weld = WeldInitiator.createWeld();
WeldInitiator.Builder builder = WeldInitiator.from(weld);
weldInit(testInstance, context, weld, builder);
// Apply discovered enrichers
for (WeldJunitEnricher enricher : getEnrichersFromStore(context)) {
String property = System.getProperty(enricher.getClass().getName());
if (property == null || Boolean.parseBoolean(property)) {
enricher.enrich(testInstance, context, weld, builder);
}
}
initiator = builder.build();
}
setInitiatorToStore(context, initiator);
// this ensures the test class is injected into
// in case of nested tests, this also injects into any outer classes
Set<Object> enclosingClasses = getInstancesToInjectToFromRootStore(context);
if (enclosingClasses != null) {
initiator.addObjectsToInjectInto(enclosingClasses);
}
// and finally, init Weld
setContainerToStore(context, initiator.initWeld(testInstance));
}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
doFinally(context, TestInstance.Lifecycle.PER_METHOD);
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
doFinally(context, TestInstance.Lifecycle.PER_CLASS);
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
doFinally(context, TestInstance.Lifecycle.PER_CLASS);
}
protected void doFinally(ExtensionContext context, TestInstance.Lifecycle lifecycleForClean) {
ProcessEngine processEngine = getProcessEngine(context);
ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
boolean isAsyncHistoryEnabled = processEngineConfiguration.isAsyncHistoryEnabled();
if (isAsyncHistoryEnabled) {
ManagementService managementService = processEngine.getManagementService();
List<HistoryJob> jobs = managementService.createHistoryJobQuery().list();
for (HistoryJob job : jobs) {
managementService.deleteHistoryJob(job.getId());
}
}
HistoryManager asyncHistoryManager = null;
try {
if (isAsyncHistoryEnabled) {
processEngineConfiguration.setAsyncHistoryEnabled(false);
asyncHistoryManager = processEngineConfiguration.getHistoryManager();
processEngineConfiguration
.setHistoryManager(new DefaultHistoryManager(processEngineConfiguration,
processEngineConfiguration.getHistoryLevel(), processEngineConfiguration.isUsePrefixId()));
}
String annotationDeploymentKey = context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY;
String deploymentIdFromDeploymentAnnotation = getStore(context).get(annotationDeploymentKey, String.class);
if (deploymentIdFromDeploymentAnnotation != null) {
TestHelper.annotationDeploymentTearDown(processEngine, deploymentIdFromDeploymentAnnotation, context.getRequiredTestClass(),
context.getRequiredTestMethod().getName());
getStore(context).remove(annotationDeploymentKey);
}
AnnotationSupport.findAnnotation(context.getTestMethod(), CleanTest.class)
.ifPresent(cleanTest -> removeDeployments(processEngine.getRepositoryService()));
AbstractFlowableTestCase.cleanDeployments(processEngine);
if (context.getTestInstanceLifecycle().orElse(TestInstance.Lifecycle.PER_METHOD) == lifecycleForClean
&& processEngineConfiguration.isUsingRelationalDatabase()) { // the logic only is applicable to a relational database with tables
cleanTestAndAssertAndEnsureCleanDb(context, processEngine);
}
} finally {
if (isAsyncHistoryEnabled) {
processEngineConfiguration.setAsyncHistoryEnabled(true);
processEngineConfiguration.setHistoryManager(asyncHistoryManager);
}
processEngineConfiguration.getClock().reset();
}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
doFinally(context, TestInstance.Lifecycle.PER_METHOD);
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
doFinally(context, TestInstance.Lifecycle.PER_CLASS);
}
boolean isPerClass(final ExtensionContext context) {
return context.getTestInstanceLifecycle()
.map(it -> it.equals(TestInstance.Lifecycle.PER_CLASS))
.orElse(false);
}
@Override
public Optional<TestInstance.Lifecycle> getTestInstanceLifecycle() {
return Optional.empty();
}
@Override
public Optional<TestInstance.Lifecycle> getTestInstanceLifecycle() {
throw new UnsupportedOperationException();
}
@Override
public Optional<TestInstance.Lifecycle> getTestInstanceLifecycle() {
throw new UnsupportedOperationException();
}
@Override
public Optional<TestInstance.Lifecycle> getTestInstanceLifecycle() {
throw new UnsupportedOperationException();
}