forked from junit-team/junit5
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Björn Michael <[email protected]> See junit-team#3367 See junit-team#3592
- Loading branch information
Showing
9 changed files
with
462 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
/* | ||
* Copyright 2015-2023 the original author or authors. | ||
* | ||
* All rights reserved. This program and the accompanying materials are | ||
* made available under the terms of the Eclipse Public License v2.0 which | ||
* accompanies this distribution and is available at | ||
* | ||
* https://www.eclipse.org/legal/epl-v20.html | ||
*/ | ||
|
||
package example; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
||
import java.sql.Connection; | ||
import java.sql.DriverManager; | ||
import java.sql.ResultSet; | ||
import java.sql.SQLException; | ||
|
||
import org.junit.jupiter.api.AutoClose; | ||
import org.junit.jupiter.api.Disabled; | ||
import org.junit.jupiter.api.Test; | ||
|
||
@Disabled | ||
// tag::user_guide_example[] | ||
class AutoCloseDemo { | ||
|
||
@AutoClose | ||
Connection connection = getJdbcConnection("jdbc:mysql://localhost/testdb"); | ||
|
||
@Test | ||
void usersTableHasEntries() throws SQLException { | ||
ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM users"); | ||
|
||
assertTrue(resultSet.next()); | ||
} | ||
|
||
// ... | ||
// end::user_guide_example[] | ||
private static Connection getJdbcConnection(String url) { | ||
try { | ||
return DriverManager.getConnection(url); | ||
} | ||
catch (SQLException ex) { | ||
throw new RuntimeException(ex); | ||
} | ||
} | ||
|
||
} |
59 changes: 59 additions & 0 deletions
59
junit-jupiter-api/src/main/java/org/junit/jupiter/api/AutoClose.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
/* | ||
* Copyright 2015-2023 the original author or authors. | ||
* | ||
* All rights reserved. This program and the accompanying materials are | ||
* made available under the terms of the Eclipse Public License v2.0 which | ||
* accompanies this distribution and is available at | ||
* | ||
* https://www.eclipse.org/legal/epl-v20.html | ||
*/ | ||
|
||
package org.junit.jupiter.api; | ||
|
||
import java.lang.annotation.Documented; | ||
import java.lang.annotation.ElementType; | ||
import java.lang.annotation.Retention; | ||
import java.lang.annotation.RetentionPolicy; | ||
import java.lang.annotation.Target; | ||
|
||
import org.apiguardian.api.API; | ||
import org.junit.jupiter.api.extension.ExtendWith; | ||
|
||
/** | ||
* The {@code AutoClose} annotation is used to automatically close resources | ||
* used in tests. | ||
* | ||
* <p>This annotation should be applied to fields within test classes. It | ||
* indicates that the annotated resource should be automatically closed after | ||
* the test execution. | ||
* | ||
* <p>By default, the {@code AutoClose} annotation expects the annotated | ||
* resource to provide a {@code close()} method that will be invoked for closing | ||
* the resource. However, developers can customize the closing behavior by | ||
* providing a different method name through the {@link #value} attribute. For | ||
* example, setting {@code value = "shutdown"} will look for a method named | ||
* {@code shutdown()} to close the resource. When multiple annotated resources | ||
* exist the order of closing them is unspecified. | ||
* | ||
* @since 5.11 | ||
* @see java.lang.annotation.Retention | ||
* @see java.lang.annotation.Target | ||
*/ | ||
@Target(ElementType.FIELD) | ||
@Retention(RetentionPolicy.RUNTIME) | ||
@Documented | ||
@ExtendWith(AutoCloseExtension.class) | ||
@API(status = API.Status.EXPERIMENTAL, since = "5.11") | ||
@SuppressWarnings("exports") | ||
public @interface AutoClose { | ||
|
||
/** | ||
* Specifies the name of the method to invoke for closing the resource. | ||
* | ||
* <p>The default value is {@code close}. | ||
* | ||
* @return the method name for closing the resource | ||
*/ | ||
String value() default "close"; | ||
|
||
} |
99 changes: 99 additions & 0 deletions
99
junit-jupiter-api/src/main/java/org/junit/jupiter/api/AutoCloseExtension.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
/* | ||
* Copyright 2015-2023 the original author or authors. | ||
* | ||
* All rights reserved. This program and the accompanying materials are | ||
* made available under the terms of the Eclipse Public License v2.0 which | ||
* accompanies this distribution and is available at | ||
* | ||
* https://www.eclipse.org/legal/epl-v20.html | ||
*/ | ||
|
||
package org.junit.jupiter.api; | ||
|
||
import static org.junit.platform.commons.util.AnnotationUtils.findAnnotatedFields; | ||
|
||
import java.lang.reflect.Field; | ||
import java.lang.reflect.Method; | ||
import java.util.function.Predicate; | ||
|
||
import org.junit.jupiter.api.extension.AfterAllCallback; | ||
import org.junit.jupiter.api.extension.ExtensionConfigurationException; | ||
import org.junit.jupiter.api.extension.ExtensionContext; | ||
import org.junit.jupiter.api.extension.ExtensionContext.Namespace; | ||
import org.junit.jupiter.api.extension.ExtensionContext.Store; | ||
import org.junit.jupiter.api.extension.TestInstancePreDestroyCallback; | ||
import org.junit.platform.commons.logging.Logger; | ||
import org.junit.platform.commons.logging.LoggerFactory; | ||
import org.junit.platform.commons.util.ExceptionUtils; | ||
import org.junit.platform.commons.util.ReflectionUtils; | ||
|
||
/** | ||
* {@code AutoCloseExtension} is a JUnit Jupiter extension that closes resources | ||
* if a field in a test class is annotated with {@link AutoClose @AutoClose}. | ||
* | ||
* <p>Consult the Javadoc for {@link AutoClose @AutoClose} for details on the | ||
* contract. | ||
* | ||
* @since 5.11 | ||
* @see AutoClose | ||
*/ | ||
class AutoCloseExtension implements AfterAllCallback, TestInstancePreDestroyCallback { | ||
|
||
private static final Logger logger = LoggerFactory.getLogger(AutoCloseExtension.class); | ||
private static final Namespace NAMESPACE = Namespace.create(AutoClose.class); | ||
|
||
@Override | ||
public void afterAll(ExtensionContext context) { | ||
Store contextStore = context.getStore(NAMESPACE); | ||
Class<?> testClass = context.getRequiredTestClass(); | ||
|
||
registerCloseables(contextStore, testClass, null); | ||
} | ||
|
||
@Override | ||
public void preDestroyTestInstance(ExtensionContext context) { | ||
Store contextStore = context.getStore(NAMESPACE); | ||
|
||
for (Object instance : context.getRequiredTestInstances().getAllInstances()) { | ||
registerCloseables(contextStore, instance.getClass(), instance); | ||
} | ||
} | ||
|
||
private void registerCloseables(Store contextStore, Class<?> testClass, Object testInstance) { | ||
Predicate<Field> predicate = testInstance == null ? ReflectionUtils::isStatic : ReflectionUtils::isNotStatic; | ||
findAnnotatedFields(testClass, AutoClose.class, predicate).forEach(field -> { | ||
try { | ||
contextStore.put(field, asCloseableResource(testInstance, field)); | ||
} | ||
catch (Throwable t) { | ||
throw ExceptionUtils.throwAsUncheckedException(t); | ||
} | ||
}); | ||
} | ||
|
||
private static Store.CloseableResource asCloseableResource(Object testInstance, Field field) { | ||
return () -> { | ||
Object toBeClosed = ReflectionUtils.tryToReadFieldValue(field, testInstance).get(); | ||
if (toBeClosed == null) { | ||
logger.warn(() -> "@AutoClose couldn't close object for field " + getQualifiedFieldName(field) | ||
+ " because it was null."); | ||
return; | ||
} | ||
invokeCloseMethod(field, toBeClosed); | ||
}; | ||
} | ||
|
||
private static void invokeCloseMethod(Field field, Object toBeClosed) { | ||
String methodName = field.getAnnotation(AutoClose.class).value(); | ||
Method closeMethod = ReflectionUtils.findMethod(toBeClosed.getClass(), methodName).orElseThrow( | ||
() -> new ExtensionConfigurationException( | ||
"@AutoClose failed to close object for field " + getQualifiedFieldName(field) + " because the " | ||
+ methodName + "() method could not be " + "resolved.")); | ||
ReflectionUtils.invokeMethod(closeMethod, toBeClosed); | ||
} | ||
|
||
private static String getQualifiedFieldName(Field field) { | ||
return field.getDeclaringClass().getName() + "." + field.getName(); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.