PHPUnit Stub不返回所需的值

时间:2014-04-08 08:12:39

标签: 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()
    {
        $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();

    }
}

1 个答案:

答案 0 :(得分:0)

正如评论者所说,你只需返回所需的值。

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