我想做一些单元测试,但我在测试静态方法方面很挣扎。我的问题是,在我的程序中,我通过 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);