PHPUnit存根不返回所需的值
我有下面的单元测试,但我没有得到所需的值。也许我不明白这是怎么正确工作的PHPUnit存根不返回所需的值,php,oop,unit-testing,phpunit,stubs,Php,Oop,Unit Testing,Phpunit,Stubs,我有下面的单元测试,但我没有得到所需的值。也许我不明白这是怎么正确工作的 class TestClass { public function getData() { $id = 1123; return $id; } } class Test_ClassTesting extends PHPUnit_Framework_TestCase { public function test_addData() {
class TestClass
{
public function getData()
{
$id = 1123;
return $id;
}
}
class Test_ClassTesting extends PHPUnit_Framework_TestCase
{
public function test_addData()
{
$stub = $this->getMock('TestClass');
$stub
->expects($this->any())
->method('getData')
->will($this->returnValue('what_should_i_put_here_to_get id from TESTCLASS'));
$y = $stub->getData();
}
}
正如评论者所说,您只需返回所需的值
class TestClass
{
public function getData()
{
$id = 1123;
return $id;
}
}
class Test_ClassTesting extends PHPUnit_Framework_TestCase
{
public function test_addData()
{
$stub = $this->getMock('TestClass'); // Original Class is not used now
$stub
->expects($this->any())
->method('getData')
->will($this->returnValue(4444)); // Using different number to show stub works, not actual function
$this->assertEquals(4444, $stub->getData());
}
public function test_addDataWithoutStub()
{
$object = new TestClass();
$this->assertEquals(1123, $object->getData());
}
}
现在还不太清楚你想要完成什么。如果需要存根,则在
returnValue
中硬编码存根值。如果您想获得1123
值,那么只需实例化TestClass
并放弃mock/stub的使用。还不清楚您要测试什么,因为代码段中没有断言。您的代码段工作正常。您应该在$this->returnValue()