我是 PHP 单元的新手,现在我进退两难了。
函数结构是这样的:
function myfunc($arg) {
$data = $anotherobject->myfunc2($arg);
$diffdata = $anotherobject->myfunc3($arg);
return $data. " ".arg. " ". $diffdata;
}
我怎样才能验证输出是它应该是什么?
编辑:贾西尔当然也是对的。单元测试的重点是测试尽可能小的单元。因此,您还将进行测试以涵盖 myfunc2() 和 myfunc3()。
编辑结束
使用 stub,您可以设置 myfunc2() 和 myfunc3() 以返回已知值。然后,您可以像往常一样断言 myfunc 的返回。
类似于以下内容:
<?php
require_once 'SomeClass.php';
class StubTest extends PHPUnit_Framework_TestCase
{
public function testStub()
{
// Create a stub for the SomeClass class.
$stub = $this->getMock('SomeClass');
// Configure the stub.
$stub->expects($this->any())
->method('myfunc2')
->will($this->returnValue('foo'));
$stub->expects($this->any())
->method('myfunc3')
->will($this->returnValue('bar'));
// Calling $stub->doSomething() will now return
// 'foo'.
$this->assertEquals('foo somearg bar', $stub->myfunc('somearg'));
}
}
?>
您应该只测试 myfunc() 输出。如果您需要测试 myfunc2()、myfunct3(),请对它们进行单独测试。
function test_myfunc() {
...
}
function test_myfunc2() {
...
}
function test_myfunc3() {
...
}