简体   繁体   English

对调用返回实体页面的方法的方法进行单元测试

[英]Unit testing a method which calls a method returning a page of an entitiy

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).我想测试以下方法,因为我知道对 findAllByMerchantId() 方法的底层调用返回固定数量的结果(具有固定数量实体的页面)。

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?如何模拟 findAllByMerchantId() 调用的响应,以在页面中返回固定数量的结果?

PS Beginner at unit testing.. PS单元测试初学者..

You can use mockito together with junit .您可以将mockitojunit一起使用。 Mockito is the framework we are going to use for mocking objects and stubing methods. Mockito 是我们将用于 mocking 对象和存根方法的框架。 Junit for running the test. Junit 用于运行测试。

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查看以下链接了解更多信息: https://www.vogella.com/tutorials/Mockito/article.html

@Mock public Page findAllByMerchantId(merchantId, pageRequest) throws IOException{ //create object of desired class and return. @Mock public Page findAllByMerchantId(merchantId, pageRequest) throws IOException{ //创建所需 class 的 object 并返回。 return obj;返回对象; } }

You can try with above approach.您可以尝试使用上述方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM