I want to test a class that connects to an URL to parse html files (I am using Jsoup). The issue is that I do not know how to test this. I know that PowerMockito allows to do so, but I would prefer to avoid it if possible, by refactoring the code and test only important parts.
Here is the pieces of code I want to unit test:
@Service
public class EurLexHtmlToHtmlService extends BaseHtmlToHtml {
private static final String eurlex_URL = "https://eur-lex.europa.eu/";
@Override
public InputStream urlToHtml(String url, boolean hasOnlyOneSheet, boolean hasBorders) throws IOException {
Document document = getDocument(url);
Element content = document.body();
Element cssLink = document.select("link").last();
String cssHref = cssLink.attr("href").replace("./../../../../", "");
//Method of BaseHtmlToHtml
addStyle(url, content, cssHref);
// Method of BaseHtmlToHtml
return toInputStream(content);
}
}
public abstract class BaseHtmlToHtml implements HtmlToHtmlService {
@Autowired
HtmlLayout htmlLayout;
protected ByteArrayInputStream toInputStream(Element content) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(content.outerHtml().getBytes());
outputStream.close();
return new ByteArrayInputStream(outputStream.toByteArray());
}
protected void addStyle(String url, Element content, String cssHref) throws IOException {
Document cssDoc = getDocument(url + cssHref);
Elements cssElements = cssDoc.getAllElements();
content.append(htmlLayout.getOpenStyleTag() + cssElements.outerHtml() + htmlLayout.getCloseStyleTag());
}
protected Document getDocument(String url) throws IOException {
return Jsoup.connect(url).get();
}
}
The issue is that I do not know how to decouple my methods to be able to test without having to call Jsoup.connect(url).get