001 package org.junit.runner.manipulation;
002
003 import java.util.ArrayList;
004 import java.util.Collection;
005 import java.util.Collections;
006 import java.util.Comparator;
007 import java.util.List;
008
009 import org.junit.runner.Description;
010
011 /**
012 * A <code>Sorter</code> orders tests. In general you will not need
013 * to use a <code>Sorter</code> directly. Instead, use
014 * {@link org.junit.runner.Request#sortWith(Comparator)}.
015 *
016 * @since 4.0
017 */
018 public class Sorter extends Ordering implements Comparator<Description> {
019 /**
020 * NULL is a <code>Sorter</code> that leaves elements in an undefined order
021 */
022 public static final Sorter NULL = new Sorter(new Comparator<Description>() {
023 public int compare(Description o1, Description o2) {
024 return 0;
025 }
026 });
027
028 private final Comparator<Description> comparator;
029
030 /**
031 * Creates a <code>Sorter</code> that uses <code>comparator</code>
032 * to sort tests
033 *
034 * @param comparator the {@link Comparator} to use when sorting tests
035 * @since 4.0
036 */
037 public Sorter(Comparator<Description> comparator) {
038 this.comparator = comparator;
039 }
040
041 /**
042 * Sorts the tests in <code>target</code> using <code>comparator</code>.
043 *
044 * @since 4.0
045 */
046 @Override
047 public void apply(Object target) {
048 /*
049 * Note that all runners that are Orderable are also Sortable (because
050 * Orderable extends Sortable). Sorting is more efficient than ordering,
051 * so we override the parent behavior so we sort instead.
052 */
053 if (target instanceof Sortable) {
054 Sortable sortable = (Sortable) target;
055 sortable.sort(this);
056 }
057 }
058
059 public int compare(Description o1, Description o2) {
060 return comparator.compare(o1, o2);
061 }
062
063 /**
064 * {@inheritDoc}
065 *
066 * @since 4.13
067 */
068 @Override
069 protected final List<Description> orderItems(Collection<Description> descriptions) {
070 /*
071 * In practice, we will never get here--Sorters do their work in the
072 * compare() method--but the Liskov substitution principle demands that
073 * we obey the general contract of Orderable. Luckily, it's trivial to
074 * implement.
075 */
076 List<Description> sorted = new ArrayList<Description>(descriptions);
077 Collections.sort(sorted, this); // Note: it would be incorrect to pass in "comparator"
078 return sorted;
079 }
080
081 /**
082 * {@inheritDoc}
083 *
084 * @since 4.13
085 */
086 @Override
087 boolean validateOrderingIsCorrect() {
088 return false;
089 }
090 }