Search code examples
javajmockit

Use JMockit to mock Arrays.sort() methods in a class


I try to mock Arrays.sort methods to make sure the implementation in the QuickSort class doesn't make use of Arrays.sort. How can I do this? This is my try, which results in a java.lang.StackOverflowError

  @Test
  public void testQuickSort() {

    Integer[] array = {3, -7, 10, 3, 70, 20, 5, 1, 90, 410, -3, 7, -52};
    Integer[] sortedArray = {-52, -7, -3, 1, 3, 3, 5, 7, 10, 20, 70, 90, 410};
    QuickSort<Integer> quicksort = new QuickSort<>();

    new Expectations(Arrays.class) {{
        Arrays.sort((Integer[]) any);
    }};

    quicksort.quicksort(array);

    // some asserts
    // assertArrayEquals(sortedArray, array);
    // ...
  }

Solution

  • I was able to mock a static method this way:

    new MockUp<Arrays>() {
        @Mock
        public void sort(Object[] o) {
             System.out.println("Oh no.");
        }       
    };
    

    Source