现在我想使用Junit 5 + Mockito 4.x版本+ Mockito-inline 4.x版本,而不是Junit 4 + PowerMock 2.0.9
因为Junit 5不支持PowerMock,Mockito-inline也可以模拟静态,看起来它不再需要PowerMock了。
但是,当我使用Mockit来模拟静态时,我希望使用与Powermock相同的效果。
这是我的代码的一部分,它可以工作。
@Test
void get_report_page() {
ReportPageRequest reportPageRequest = prepare_request();
prepare_reportPage(context, 9999L, pageable);
when(reportConverter.toReportSpecification(user, reportPageRequest)).thenReturn(reportSpecification);
when(PageRequest.of(1, 100)).thenReturn(pageRequest);
when(reportRepository.findAll(reportSpecification, pageRequest)).thenReturn(reportPage);
when(reportConverter.toReportPageResponse(context)).thenReturn(reportPageResponses);
pageMockedConstruction = Mockito.mockConstruction(PageImpl.class,
withSettings().useConstructor(reportPageResponses, pageable, 9999L), (mock, context) -> {
when(mock.getTotalElements()).thenReturn(123456L);
when(mock.getTotalPages()).thenReturn(1);
when(mock.getContent()).thenReturn(reportPageResponses);
});
Page<ReportPageResponse> actual = sut.getReportPage(user, reportPageRequest);
assertThat(actual.getTotalElements()).isEqualTo(123456L);
assertThat(actual.getTotalPages()).isEqualTo(1);
assertThat(actual.getContent()).isEqualTo(reportPageResponses);
}
}
而我的问题是我只是可以验证模拟静态对象的行为,却无法验证结果,这是我试
pageMockedConstruction = Mockito.mockConstruction(PageImpl.class,
withSettings().useConstructor(reportPageResponses, pageable, 9999L), (mock, context) -> {
when(mock.getTotalElements()).thenReturn(123456L);
when(mock.getTotalPages()).thenReturn(1);
when(mock.getContent()).thenReturn(reportPageResponses);
});
// I thought here will be the same mock object
// when expected and actual will throught the Mockito.mockConstruction, but actually generate the different object
PageImpl<ReportPageResponse> expected = new PageImpl<>(this.reportPageResponses, pageable, 9999L);
Page<ReportPageResponse> actual = sut.getReportPage(user, reportPageRequest);
// Here will be wrong, because actual and expected has different hashCode
Assertions.assertThat(actual).isEqualTo(expected);
我研究了这么多文章,但我找不到答案。
有人遇到过同样的问题吗?
1条答案
按热度按时间dxpyg8gm1#
Powermock.whenNew
和Mockito.mockConstruction
的主要区别在于,Mokito
在构造函数调用时,每次示例化新对象时都会创建一个新的mock,但是Powermock.whenNew
可以被配置为在构造多个对象时总是返回一个mock。根据documentation:
表示所表示类型的任何对象构造的模拟。在模拟构造的范围内,调用任何侦听器都将生成一个模拟,该模拟将在生成此范围时按指定进行准备。还可以通过此示例接收该模拟。
您可以使用
MockedConstruction<T>.constructed()
来获取上下文中所有生成的mock。它们可用于验证。检查行为的测试示例: