gpt4 book ai didi

java - 带有 Pageable 对象的 Mockito

转载 作者:行者123 更新时间:2023-12-01 21:24:01 34 4
gpt4 key购买 nike

我有下面的代码。

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));
}
}

我想 mock 它。我在下面使用过,但它给出了 -

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);

将会失败。

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

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

关于java - 带有 Pageable 对象的 Mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58839592/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com