2
class Documentation
{
    private $_text;

    public function __construct($text)
    {
        $this->_text = $text;
    }

    public function generate()
    {
        return new \DOMElement('documentation', $this->_text);
    }
}

我能想到的显而易见的解决方案是创建 new DOMDocument,附加generate()函数调用的结果并使用 与预期的元素进行比较$this->assertEqualXMLStructure,但由于某种原因,我不喜欢它,并且确信还有其他选择。

有任何想法吗?

UPD:似乎我错过了一些重要的事情:我要确保的是返回具有特定内容的特定类型的元素。怎么做?

更新 2

这是我目前可以创建的,但它很丑,不是吗?

public function testGenerate()
{
    $expected = new \DOMDocument();
    $expected->loadXML('<?xml version="1.0" encoding="utf-8"?><documentation>foo</documentation>');

    $documentation = new Documentation('foo');
    $actual = new \DOMDocument('1.0', 'utf-8');
    $actual->appendChild($documentation->generate());

    $this->assertEqualXMLStructure($expected, $actual);
}
4

1 回答 1

5

这是一个如此简单的类,几乎没有任何可能出错的地方。代码中根本没有分支,所有方法的圈复杂度都是1。真的没有必要为这么简单的类编写测试套件。

但是,您可以使用 PHPUnit 断言 generate() 方法返回一个 DOMElement 对象,并且该元素的子节点是一个文本对象,并且该文本对象与输入文本匹配。

真的没有什么意义。

编辑添加:这是进行测试的示例方法(假设 PHPUnit 作为测试运行器)。它没有经过测试,因此语法可能是错误的,但它应该让您对测试过程有所了解。

As you can see, this method is longer than the class being tested! I'm a big fan of unit testing, but in this particular case it seems to be overkill. Unless you have a code-coverage quota you must hit, or unless you're especially cautious and want some assurance regarding your class, I just wouldn't bother in this particular case.

public function testGenerate ()
{
    $expected = 'The quick brown fox jumps over the lazy dog';
    $this -> object = new Documentation ($expected);
    $actual = $this -> object -> generate ();

    // Check we got a DOM Element object
    $this -> assertInstanceOf ('\DOMElement', $actual);

    // Check that our DOM element is of the Documentation type
    $this -> assertEquals ('documentation', $actual -> tagName);

    // Check that our Documentation element has a single text node child
    $this -> assertEquals (1, $actual -> childNodes -> length);
    $this -> assertInstanceOf ('\DOMText', $actual -> firstChild);

    // Check that the text node has the value we passed in originally
    $this -> assertEquals ($expected, $actual -> firstChild -> wholeText);
}
于 2012-10-16T07:34:11.890 回答