我有一些java基类,里面有1个方法:
public class SB {
@SneakyThrows
public Document downloadHtml(String url) {
return Jsoup.connect(url)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.2651.98")
.get();
}
}
我还有另一个类扩展 SB 并实现一些接口:
public class TScrapperProvider extends SB implements Scrapper {
private static final Logger logger = LoggerFactory.getLogger(TelemagazynScrapperProvider.class);
@Override
public List<Channel> getAllChannels() {
Document doc = downloadHtml("URL");
...
}
@Override
public List<TVShow> getChannelScheduleForDate(LocalDate date, Channel channel) {
Document doc = downloadHtml("URL");
....
}
}
然后我有一个单元测试类,我想在其中测试
TScrapperProvider
中的两种方法,为了做到这一点,我想模拟 SB 中的 downloadHtml
方法:
@Test
public void testGetAllChannels() {
SB sBase = mock(SB.class);
when(sBase.downloadHtml("https://example.html")).thenReturn(createMockChannelsPage());
Scrapper scrapper = new TScrapperProvider();
List<Channel> channels = scrapper.getAllChannels();
verify(sBase, times(1)).downloadHtml("https://example.html");
assertEquals(createExpectedChannels(), channels);
}
不幸的是,
verify
失败并出现Actually, there were zero interactions with this mock.
,我在结果中看到结果来自真实页面,而不是来自我的模拟。
我怎样才能调用模拟而不是真正的downloadHtml
方法?
您需要使用
spy
。
@Test
public void testGetAllChannels() {
TScrapperProvider scrapper = spy(new TScrapperProvider());
when(sBase.downloadHtml("https://example.html")).thenReturn(createMockChannelsPage());
List<Channel> channels = scrapper.getAllChannels();
verify(sBase, times(1)).downloadHtml("https://example.html");
assertEquals(createExpectedChannels(), channels);
}