具有可分页对象的Mockito

时间:2019-11-13 14:44:21

标签: java mockito powermock

我有一个下面的代码。

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..

1 个答案:

答案 0 :(得分:0)

如您所说,您不是在模拟Sort.by,返回的值不是模拟值和一行

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

将失败。

可以使用PowerMockito模拟Sort.by,但我建议不要模拟Sort.by,而是返回模拟作为{{1}的返回对象}

pageable.getSort()