View Javadoc
1   package org.junit.internal;
2   
3   import java.lang.reflect.Method;
4   import java.util.Arrays;
5   import java.util.Comparator;
6   
7   import org.junit.FixMethodOrder;
8   
9   public class MethodSorter {
10      /**
11       * DEFAULT sort order
12       */
13      public static final Comparator<Method> DEFAULT = new Comparator<Method>() {
14          public int compare(Method m1, Method m2) {
15              int i1 = m1.getName().hashCode();
16              int i2 = m2.getName().hashCode();
17              if (i1 != i2) {
18                  return i1 < i2 ? -1 : 1;
19              }
20              return NAME_ASCENDING.compare(m1, m2);
21          }
22      };
23  
24      /**
25       * Method name ascending lexicographic sort order, with {@link Method#toString()} as a tiebreaker
26       */
27      public static final Comparator<Method> NAME_ASCENDING = new Comparator<Method>() {
28          public int compare(Method m1, Method m2) {
29              final int comparison = m1.getName().compareTo(m2.getName());
30              if (comparison != 0) {
31                  return comparison;
32              }
33              return m1.toString().compareTo(m2.toString());
34          }
35      };
36  
37      /**
38       * Gets declared methods of a class in a predictable order, unless @FixMethodOrder(MethodSorters.JVM) is specified.
39       *
40       * Using the JVM order is unwise since the Java platform does not
41       * specify any particular order, and in fact JDK 7 returns a more or less
42       * random order; well-written test code would not assume any order, but some
43       * does, and a predictable failure is better than a random failure on
44       * certain platforms. By default, uses an unspecified but deterministic order.
45       *
46       * @param clazz a class
47       * @return same as {@link Class#getDeclaredMethods} but sorted
48       * @see <a href="http://bugs.sun.com/view_bug.do?bug_id=7023180">JDK
49       *      (non-)bug #7023180</a>
50       */
51      public static Method[] getDeclaredMethods(Class<?> clazz) {
52          Comparator<Method> comparator = getSorter(clazz.getAnnotation(FixMethodOrder.class));
53  
54          Method[] methods = clazz.getDeclaredMethods();
55          if (comparator != null) {
56              Arrays.sort(methods, comparator);
57          }
58  
59          return methods;
60      }
61  
62      private MethodSorter() {
63      }
64  
65      private static Comparator<Method> getSorter(FixMethodOrder fixMethodOrder) {
66          if (fixMethodOrder == null) {
67              return DEFAULT;
68          }
69  
70          return fixMethodOrder.value().getComparator();
71      }
72  }