-3
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try
{
    builder = factory.newDocumentBuilder();
}
catch (ParserConfigurationException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}
try
{
    doc = builder.parse(entity.getContent());
}
catch (IllegalStateException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}
catch (SAXException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我正在使用 dom 将 xml 文件解析为字符串。如何编写单元测试以达到预期的 100% 行覆盖率。我正在使用每个模拟。

4

2 回答 2

1

You don't, because it's pointless.

If you have a manager who doesn't understand that, then here's how to test:

  • DocumentBuilderFactory describes the mechanism used to configure a parser. By changing a system property, you can use your own (mock) class as a factory. And it can throw that exception.
  • SaxException is thrown by malformed XML. Create some malformed XML and pass it to your code.
  • IllegalStateException is thrown when your argument is null. So pass null

I should correct myself: it's not pointless. If you do succeed in getting 100% coverage, you'll discover that your exception handling should be fixed. As written, your code just keeps running (until it gets a NPE, that is) after an exception, which it shouldn't do.

于 2013-08-22T16:20:28.947 回答
0

IllegalStateException将从空 URI 抛出。

SAXException如果发生任何解析器错误(例如格式不正确的文档),将被抛出。

ParserConfigurationException只有当你给工厂的配置阻止它创建对象时才会被抛出。

但是,这些异常实际上并不需要测试,因为您所做的只是打印堆栈跟踪。并非总是需要 100% 的代码覆盖率,尤其是在这种情况下,您只需要测试 Java 库的已知功能。

如果您的异常中有逻辑,则可以通过将其拉出到方法中来测试逻辑。

例如

public void printStackTrace(Exception e){
    e.printStackTrace();
}

这是一种易于测试的方法,不需要您找到在代码的不同部分触发异常的方法。

于 2013-08-22T16:19:17.750 回答