【问题标题】:PHPUnit Stub does not return needed valuePHPUnit Stub 不返回所需的值
【发布时间】:2014-05-20 19:23:23
【问题描述】:

我有以下单元测试,但我没有取回所需的值。也许我不明白这是如何正常工作的。

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

    }
}

【问题讨论】:

  • 不太清楚您要完成什么。如果你想要一个存根,那么在returnValue 中硬编码一个存根值。如果你想获得1123 值,那么只需实例化TestClass 并放弃使用模拟/存根。
  • 也不清楚您要测试什么,因为您的 sn-p 中没有断言。
  • 您的代码 sn-p 工作正常。您应该将测试所需的任何 id 值作为参数放入 $this->returnValue()

标签: php oop unit-testing phpunit stubs


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2018-05-04
    • 2021-07-06
    • 2020-01-11
    • 1970-01-01
    • 2016-11-22
    • 2017-07-07
    相关资源
    最近更新 更多