使用抽象参数实例化对象

时间:2011-04-14 07:17:40

标签: php unit-testing oop automated-tests phpunit

interface aInterface{
     public function __construct(aClass_Abstract $a, bClass_Abstract $b){
     }
}
class Sample implements aInterface
{
     public function __construct(aClass_Abstract $a, bClass_Abstract $b){
         //implementation
         $this->init();
     }
     public function init(){
         //implementation
     }
}

如何使用PHPUnit进行测试设置?

... ...执行 测试

...
function setUp(){
    //initialize
}

3 个答案:

答案 0 :(得分:4)

在Nutshell中:使用getMockForAbstractClass创建您需要传递的fake instance个类,以便进行测试。

$a = $this->getMockForAbstractClass("aClass_Abstract");
$b = $this->getMockForAbstractClass("bClass_Abstract");
$class = new Sample($a, $b);

完整代码示例

(修正了界面定义)

<?php

interface aInterface{
     public function __construct(aClass_Abstract $a, bClass_Abstract $b);
}
class Sample implements aInterface
{
     public function __construct(aClass_Abstract $a, bClass_Abstract $b){
         //implementation
         $this->a = $a;
     }
     public function init(){
         return $this->a->myMethod();
     }
}

abstract class aClass_Abstract {
    abstract public function myMethod();
}

abstract class bClass_Abstract {}

class SampleTest extends PHPUnit_Framework_TestCase {

    public function testSetup() {

        $a = $this->getMockForAbstractClass("aClass_Abstract");
        $a->expects($this->once())->method("myMethod")->will($this->returnValue(true));
        $b = $this->getMockForAbstractClass("bClass_Abstract");
        $class = new Sample($a, $b);
        $this->assertTrue($class->init());

    }
}


/*
PHPUnit 3.5.12 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 3.25Mb
*/

答案 1 :(得分:2)

假设您要测试Sample,您将使用Stubs or Mocks

class SampleTest extends PHPUnit_Framework_TestCase
{
    public function testSomething()
    {
        $stubA = $this->getMockForAbstractClass('aClass_Abstract');
        $stubA->expects($this->any())
              ->method('abstractMethod')
              ->will($this->returnValue(TRUE));

        // do the same for bClass_Abstract

        $sample = new Sample($stubA, $stubB);
        // add an assertion for sample
    }
}

引用PHPUnit Manual on getMockForAbstractClass

  

getMockForAbstractClass()方法返回抽象类的模拟对象。给定抽象类的所有抽象方法都被模拟。这允许测试抽象类的具体方法。

有关测试双打和search StackOverflow for more information on Mocking with PHPUnit

的其他信息,请参阅该章

答案 2 :(得分:0)