带有 Pageable 对象的 Mockito

Mockito with Pageable object

我有下面的代码。

public static Pageable defaultSort(Pageable currentPageable, String defaultSort) {
        return defaultSort(currentPageable, defaultSort, Sort.Direction.ASC);
    }

    public static Pageable defaultSort(Pageable currentPageable, String defaultSort, Sort.Direction defaultDir) {
        if(currentPageable.getSort().isSorted()) {
            return currentPageable;
        } else {
            return PageRequest.of(currentPageable.getPageNumber(), currentPageable.getPageSize(), new Sort(defaultDir, defaultSort));
        }
    }

我想嘲笑它。我在下面使用,但它给出了 -

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

    at com.yyy.CustomerAssignmentServiceTest.myTest(MyTest.java:576)

这是示例测试用例

when(pageable.getSort()).thenReturn(Sort.by(order));
when(Sort.by(order).isSorted()).thenReturn(true);

when(pageable.getPageNumber()).thenReturn(0);
when(pageable.getPageSize()).thenReturn(1);
when(PageUtil.defaultSort(any(Pageable.class), "CONSTANT")).thenReturn(pageable);

myTestService.getAssignmentsForKnownContact("100", any(UUID.class), any(TestParams.class), pageable);

这是另一个错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
PageRequest cannot be returned by getSort()
getSort() should return Sort
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method..

如您所说,您不是在嘲笑 Sort.by returned 值不是嘲笑,而且行

when(Sort.by(order).isSorted()).thenReturn(true);

会失败。

可以 使用 PowerMockito 模拟 Sort.by 但我建议不要模拟 Sort.by 而是 return 模拟作为 pageable.getSort()

的 returned 对象
Sort sortMock = Mockito.mock(Sort.class);
when(pageable.getSort()).thenReturn(sortMock);
when(sortMock.isSorted()).thenReturn(true);