java 模拟返回 Page 接口的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45188675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:34:47 来源:igfitidea点击:
Mocking a method which returns Page interface
提问by Naanavanalla
I have a method which I need to write unit test case. The method returns a Page
type.
我有一个方法需要编写单元测试用例。该方法返回一个Page
类型。
How can I mock this method?
我该如何模拟这种方法?
Method:
方法:
public Page<Company> findAllCompany( final Pageable pageable )
{
return companyRepository.findAllByIsActiveTrue(pageable);
}
Thanks for the help
谢谢您的帮助
回答by Darshan Mehta
You can use a Mock
reponse or an actual response and then use when
, e.g.:
您可以使用 Mock
响应或实际响应,然后使用when
,例如:
Page<Company> companies = Mockito.mock(Page.class);
Mockito.when(companyRepository.findAllByIsActiveTrue(pageable)).thenReturn(companies);
Or, just instantiate the class:
或者,只需实例化该类:
List<Company> companies = new ArrayList<>();
Page<Company> pagedResponse = new PageImpl(companies);
Mockito.when(companyRepository.findAllByIsActiveTrue(pagedResponse)).thenReturn(pagedResponse);