gpt4 book ai didi

java - 在这个涉及数据分页的 Java 方法中可以对什么进行单元测试?

转载 作者:行者123 更新时间:2023-12-01 16:50:45 25 4
gpt4 key购买 nike

单元测试的初学者。以下是要测试的方法 -

public ListBeneficiaryResponseDTO getBeneficiaryOfMerchants(Long merchantId, Integer page, Integer pageSize,
String sortDirection, String sortField) {
LOGGER.info("Inside getBeneficiaryOfMerchants method");

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

为了编写测试,我想,考虑到底层方法调用工作正常,这个方法会做错什么。好吧,我不确定,但将元素放入列表时可能会出现一些错误。

因此,我想编写一个测试来确保列表 benResonseDtoList 中存在预期数量的元素。

以下是我尝试过的 -

@Test
public void testGetBeneficiariesOfMerchant() throws Exception {

Long merchantId = 2l;
List<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>();
beneficiaryList.add(getBeneficiaryDto());
beneficiaryList.add(getBeneficiaryDto());


Page<Beneficiary> beneficiaries = new PageImpl<Beneficiary>(beneficiaryList); //But I am not sure how many entries are there in the page created.
Mockito.when(beneficiaryRepository.findAllByMerchantId(any(),any())).thenReturn(beneficiaries);
KeyManager keyManager = Mockito.mock(KeyManager.class);


ListBeneficiaryResponseDTO list = beneficiaryService.getBeneficiaryOfMerchants(merchantId,1,2, "DESC","addedOn");

如果 beneficiaryList 中的元素数量与 pageOfBeneficiaries 中的条目之间存在明显的相关性,我可以对此进行测试。

最佳答案

如果我正确理解您的问题,您想了解 getBeneficiaryOfMerchants() 函数的测试场景(给定下划线函数是否正常工作)。

对于给定的

merchantId, page, pageSize, sortDirection, sortField

ListBeneficiaryResponseDTO 将被修复,我们将其称为 ListBeneficiaryResponseDTO expectedList (您必须构建它,因为您已经知道正确的输出)

所以你应该比较以下内容:-

实际输出:

ListBeneficiaryResponseDTO actualList =  beneficiaryService.getBeneficiaryOfMerchants(merchantId,1,2, "DESC","addedOn");

预期输出:ListBeneficiaryResponseDTO预期列表(上面已定义)

比较两个输出:-

  1. 逐个字段比较 actualListexpectedList

  2. 重写 ListBeneficiaryResponseDTO 类的 Equals 方法(或者您可以使用 lombok.EqualsAndHashCode 来避免样板代码)并执行以下操作:-assertEquals(**actualList**, **expectedList**)

关于java - 在这个涉及数据分页的 Java 方法中可以对什么进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61696189/

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