Created
July 6, 2021 08:56
-
-
Save jcarsique/df98e0bad9e88e8258c4ab34dad3c863 to your computer and use it in GitHub Desktop.
JUnit 4 Test Ordering
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
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
/** | |
* JUnit 4 equivalent of JUnit 5's {@code org.junit.jupiter.api.Order} | |
*/ | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target({ ElementType.METHOD }) | |
public @interface Order { | |
/** | |
* Default order value for elements not explicitly annotated with {@code @Order}. | |
* | |
* @see Order#value | |
*/ | |
int DEFAULT = 0; | |
/** | |
* The order value for the annotated element. | |
* <p>Elements are ordered based on priority where a lower value has greater | |
* priority than a higher value. For example, {@link Integer#MAX_VALUE} has | |
* the lowest priority. | |
* | |
* @see #DEFAULT | |
*/ | |
int value(); | |
} |
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
import java.util.Comparator; | |
import java.util.Optional; | |
import org.junit.runner.Description; | |
import org.junit.runner.manipulation.Ordering; | |
import org.junit.runner.manipulation.Sorter; | |
/** | |
* Order test methods by their {@link Order} annotation. The lower value has the highest priority. | |
* The tests that are not annotated get the default value {@link Order#DEFAULT}. | |
*/ | |
public class OrderAnnotation extends Sorter implements Ordering.Factory { | |
public OrderAnnotation() { | |
super(COMPARATOR); | |
} | |
@Override | |
public Ordering create(Context context) { | |
return this; | |
} | |
private static final Comparator<Description> COMPARATOR = Comparator.comparingInt( | |
description -> Optional.ofNullable(description.getAnnotation(Order.class)) | |
.map(Order::value) | |
.orElse(Order.DEFAULT)); | |
} |
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
@OrderWith(OrderAnnotation.class) | |
public class MyTest { | |
@Test | |
@Order(-1) | |
public void runBeforeNotAnnotatedTests() {} | |
@Test | |
public void notAnnotatedTestHasPriority0() {} | |
@Test | |
@Order(1) | |
public void thisTestHasPriority1() {} | |
@Test | |
@Order(2) | |
public void thisTestHasPriority2() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment