如何在单元测试中用内容数据模拟页面?

How to mock Page with content data in Unit Test?

如何return页面内容在Spring引导单元测试服务层?如何用一些值模拟此数据并稍后对其进行测试?

需要测试的服务:

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CampaignReadServiceImpl02 {

    private final CampaignRepository campaignRepository;


    public Page<Campaign> getAll(int page, int size) {

        Pageable pageable = PageRequest.of(page, size);

        Page<Campaign> pages = campaignRepository.findAll(pageable);

        return pages;
    }
}

单元测试中模拟数据的class

@Slf4j
@ExtendWith(MockitoExtension.class)
public class CampaignReadServiceTest {

    @Mock
    private CampaignRepository campaignRepository;

    private CampaignReadServiceImpl02 campaignReadServiceImpl02;

    @BeforeEach
    public void beforeEach() {
        campaignReadServiceImpl02 = new CampaignReadServiceImpl02(campaignRepository);
    }

    @Test
    public void testGetAll02() {
        log.info("Testing get all campaigns method");

        //this need to have content data inside of page.getContent(), need to be added
        Page<Campaign> page = Mockito.mock(Page.class);

        Mockito.when(campaignRepository.findAll(Mockito.any(Pageable.class))).thenReturn(page);

        Page<Campaign> result = campaignReadServiceImpl02.getAll(2, 2);

        Assertions.assertNotNull(result);

        Mockito.verify(campaignRepository, Mockito.times(1)).findAll(Mockito.any(Pageable.class));
        Mockito.verifyNoMoreInteractions(campaignRepository);
    }
}

如何模拟 Page<Campaign> page = Mockito.mock(Page.class); 以获取 result.getContent(); 当服务存储库被注入服务时..

我无法测试 result.getContent() 因为我没有存储库中的数据,maube 因为我需要将 mock Page<Campaign> pagePage.class 更改为其他内容?

如何正确模拟 Page<Campaign> page = Mockito.mock(Page.class); 稍后将 return 一些数据用于服务:result.getContent().name() 等..

最简单的方法是创建一个对象而不是模拟 class。

Page<TournamentEntity> tournamentEntitiesPage = new PageImpl<>(List.of(obj1, obj2), pageable, 0);