I would like to test the following method, for the case when I know the underlying call to findAllByMerchantId() method returns a fixed number of results (a page with fixed number of entities).
public ListBeneficiaryResponseDTO getBeneficiariesOfMerchant(Long merchantId, Integer page, Integer pageSize,
String sortDirection, String sortField) {
// default we are setting to added on desc sort
Sort sort = Sort.by(Sort.Direction.DESC,"addedOn");
if(sortField != null && sortDirection != null) {
sort = Sort.by(Sort.Direction.fromString(sortDirection),sortField);
}
Pageable pageRequest = PageRequest.of(page-1, pageSize, sort);
Page<Beneficiary> pageOfBeneficiaries = beneficiaryRepository.findAllByMerchantId(merchantId, pageRequest);
List<BeneficiaryResponseDTO> benResonseDtoList = new ArrayList<BeneficiaryResponseDTO>();
for( Beneficiary ben: pageOfBeneficiaries.getContent()) {
benResonseDtoList.add(this.getBeneficiaryResponseDTO(ben));
}
ListBeneficiaryResponseDTO formattedListBen = new ListBeneficiaryResponseDTO(pageOfBeneficiaries.getTotalPages(),pageOfBeneficiaries.getTotalElements(),pageOfBeneficiaries.getNumber(),benResonseDtoList);
return formattedListBen;
}
How do I mock the response of findAllByMerchantId() call, to return a fixed number of results in a page?
PS Beginner at unit testing..
You can use mockito
together with junit
. Mockito is the framework we are going to use for mocking objects and stubing methods. Junit for running the test.
public class Test {
@Mock
private BeneficiaryRepository beneficiaryRepository;
@Test
public void testGetBeneficiariesOfMerchant() {
//your code ...
Page<Beneficiary> pages = // your initialization
when(beneficiaryRepository.findAllByMerchantId(any(),any())).thenReturn(pages);
//your code ...
}
}
Check the link below for more info: https://www.vogella.com/tutorials/Mockito/article.html
@Mock public Page findAllByMerchantId(merchantId, pageRequest) throws IOException{ //create object of desired class and return. return obj; }
You can try with above approach.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.