gpt4 book ai didi

php - 您将如何为此类类(class)编写测试?

转载 作者:行者123 更新时间:2023-11-28 20:04:06 25 4
gpt4 key购买 nike

class Documentation
{
private $_text;

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

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

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

有什么想法吗?

UPD:似乎我错过了一些重要的事情:我想确定的是返回了具有特定内容的特定类型的元素。如何做到这一点?

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);
}

最佳答案

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

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

真的没有太多意义。

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

如您所见,这个方法比被测试的类还要长!我是单元测试的忠实拥护者,但在这种特殊情况下,它似乎有些矫枉过正。除非您有必须达到的代码覆盖率配额,或者除非您特别谨慎并希望对您的类(class)有所保证,否则我不会在这种特殊情况下打扰。

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);
}

关于php - 您将如何为此类类(class)编写测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12909550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com