Spring Boot单元测试服务层如何返回Page内容?如何用一些值模拟此数据并稍后对其进行测试?
需要测试的服务:
@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;
}
}
单元测试中模拟数据的类
@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();
当在服务中注入(inject)服务存储库时..
我无法测试 result.getContent()
因为我没有存储库中的数据,maube 因为我需要更改 mock Page<Campaign> page
与 Page.class
到别的地方?
如何正确模拟 Page<Campaign> page = Mockito.mock(Page.class);
稍后将在服务中返回一些数据:result.getContent().name() 等。
最佳答案
最简单的方法是创建一个对象而不是模拟类。
Page<TournamentEntity> tournamentEntitiesPage = new PageImpl<>(List.of(obj1, obj2), pageable, 0);
关于java - 如何在单元测试中用内容数据模拟页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72438479/