使用JMockit模拟类中的Arrays.sort()方法

时间:2018-08-02 14:29:54

标签: java jmockit

我尝试模拟Arrays.sort方法,以确保QuickSort类中的实现不使用Arrays.sort。我怎样才能做到这一点?这是我的尝试,结果是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);
    // ...
  }

2 个答案:

答案 0 :(得分:0)

您需要模拟它,并将调用Arrays.sort的时间限制为0

@Test
public void testQuickSort(@Mocked Arrays mock) {
    new Expectations() {{
        mock.sort((Integer[]) any);
        times = 0;
    }};

    quicksort.quicksort(array);
}

答案 1 :(得分:0)

我能够以这种方式模拟静态方法:

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

Source

相关问题