2013-06-04 55 views
2

我有一个具有抽象方法和具体方法的抽象类。单元测试调用具体子方法的抽象类方法

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

这个返回值如何被模拟?

因此,抽象类是

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方法,所以我想嘲笑返回值来测试 - 但它调用的方法里面?

这可能吗?

回答

3

是的,这是可能的。您的测试应该是这样的:

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

相关问题