java - 使用 PowerMock 对 Jsoup 进行单元测试
问题描述
我想做一些单元测试,但我在测试静态方法方面遇到了很多困难。我的问题是,在我的程序中,我通过 Jsoup 获得了两个不同的文档,它们用于生成一个 InputStream(一个用于提取 HTML 网页,另一个用于提取然后应用网页的特定样式)。此外,我正在使用抽象类来避免为我正在编写的每个新算法重新编写相同的代码。
这是我要测试的一段代码:
public abstract class BaseHtmlToHtml implements HtmlToHtmlService {
@Autowired
HtmlLayout htmlLayout;
protected InputStream getInputStream(Document doc, Element content, String url) throws IOException {
Element cssLink = doc.select("link").last();
String cssHref = cssLink.attr("href").replace("./../../../../", "");
//Getting document via Jsoup
Document cssDoc = getDocument(url + cssHref);
Elements cssElements = cssDoc.getAllElements();
content.append("<style>" + cssElements.outerHtml() + "</style>");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(content.outerHtml().getBytes());
outputStream.close();
return new ByteArrayInputStream(outputStream.toByteArray());
}
protected Document getDocument(String url) throws IOException {
return Jsoup.connect(url).get();
}
}
@Service
public class EurLexHtmlToHtmlService extends BaseHtmlToHtml {
private static final String eurlex_URL = "https://eur-lex.europa.eu/";
@Override
public InputStream urlToHtml(Map<String, String> params) throws IOException {
//Getting document via Jsoup
Document document = getDocument(params.get("url"));
Element content = document.body();
// Getting document via Jsoup
return getInputStream(document, content, eurlex_URL);
}
}
这是我迄今为止尝试过的:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Jsoup.class)
@SpringBootTest
class EurLexHtmlToHtmlServiceTest {
@Test
void urlToHtmlSetUpCorrectStyle() throws IOException, URISyntaxException {
Map<String, String> params = ImmutableMap.of(
"url", url,
"hasOnlyOneSheet", "false",
"hasBorders", "false"
);
Connection connection = Mockito.mock(Connection.class);
Mockito
.when(Jsoup.connect(url))
.thenReturn(connection);
mockStatic(Jsoup.class);
PowerMockito
.when(connection.get())
.thenReturn(new Document("src/test/resources/eurlexTest.html"));
PowerMockito.when(eurLexHtmlToHtml.getDocument(url))
.thenReturn(new Document("src/test/resources/eurlexTest.html"));
PowerMockito.when(eurLexHtmlToHtml.getDocument(styleUrl))
.thenReturn(new Document("src/test/resources/eurlexStyleTest.html"));
assertThat(eurLexHtmlToHtml.urlToHtml(params))
.hasContent("<style>test</style>");
}
}
但我收到以下错误消息:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
解决方案
推荐阅读
- html - 当用户调整窗口大小时,如何防止文本移动?
- mysql - 在表 2 中插入记录后更新表 1
- java - Java Scanner 在读取 unicode 文件时错过了第一行
- c++ - 在 Ubuntu (c++) 上构建项目时出现 V8 链接器错误
- javascript - 通过 chrome 扩展覆盖 window.confirm() 确认?
- arrays - 自动完成发送数据 id
- python - 在 Python 中使用“in”关键字在集合中查找项目时遇到问题
- ruby-on-rails - Select2 不加载数据
- julia - 朱莉娅的相同代码不同的结果
- angular - ng serve 不会编译