Java 带可分页对象的Mockito
我有下面的代码Java 带可分页对象的Mockito,java,mockito,powermock,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 de
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
when(Sort.by(order).isSorted()).thenReturn(true);
将失败
您可以使用模拟Sort.by
,但我建议不要模拟Sort.by
,而是将模拟作为pageable.getSort()的返回对象返回
在您的示例测试用例代码中,哪一行是MyTest.java:576
引用的?是Sort.by
使用PowerMockito模拟的,如果是,您可以为模拟设置共享该代码吗?不,我没有模拟排序。by
,我该怎么做?它的最后一行,但我无法模拟pageable=PageUtil.defaultSort(pageable,AppConst.SOMECONSTANT)代码>当我执行时(PageUtil.defaultSort(可分页,“contactTypeCode”))。然后返回(可分页)代码>,我得到org.mockito.exceptions.misusing.ErrorTypeOfReturnValue:
Sort sortMock = Mockito.mock(Sort.class);
when(pageable.getSort()).thenReturn(sortMock);
when(sortMock.isSorted()).thenReturn(true);