【问题标题】:Unit test Abstract class method that calls concrete child method单元测试调用具体子方法的抽象类方法
【发布时间】:2013-06-04 12:35:40
【问题描述】:

我有一个抽象类,它有一个抽象方法和一个具体方法。

具体方法调用抽象方法并使用其返回值。

这个返回值怎么mock?

所以抽象类是

abstract class MyAbstractClass
{
    /**
     * @return array()
     */
    abstract function tester();

    /**
     * @return array()
     */
    public function myconcrete()
    {
        $value = $this->tester();  //Should be an array

        return array_merge($value, array("a","b","c");
    }
}

我想测试 myconcrete 方法,所以我想模拟测试器的返回值 - 但它是在方法内部调用的?

这可能吗?

【问题讨论】:

    标签: php unit-testing phpunit


    【解决方案1】:

    是的,这是可能的。您的测试应如下所示:

    class MyTest extends PHPUnit_Framework_TestCase
    {    
        public function testTester() {
            // mock only the method tester all other methods will keep unchanged
            $stub = $this->getMockBuilder('MyAbstractClass')
                ->setMethods(array('tester'))
                ->getMock();
    
            // configure the stub so that tester() will return an array
            $stub->expects($this->any())
                ->method('tester')
                ->will($this->returnValue(array('1', '2', '3')));
    
            // test myconcrete()
            $result = $stub->myconcrete();    
    
            // assert result is the correct array
            $this->assertEquals($result, array(
                '1', '2', '3', 'a', 'b', 'c' 
            )); 
        }
    }
    

    请注意,我使用的是 PHPUnit 3.7.10

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多