开发者

Instantiate object with abstract parameters

interface aInterface{
     public function __construct(aClass_Abst开发者_如何学运维ract $a, bClass_Abstract $b){
     }
}
class Sample implements aInterface
{
     public function __construct(aClass_Abstract $a, bClass_Abstract $b){
         //implementation
         $this->init();
     }
     public function init(){
         //implementation
     }
}

How to setup this on testing using PHPUnit?

...implementation... test

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


In a Nutshell: Use getMockForAbstractClass to create a fake instance of the classes you need to pass in so you can test them.

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

Full code example

(Fixed the interface definition)

<?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
*/


Assuming you want to test Sample you will be using 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
    }
}

Quoting the PHPUnit Manual on getMockForAbstractClass:

The getMockForAbstractClass() method returns a mock object for an abstract class. All abstract methods of the given abstract class are mocked. This allows for testing the concrete methods of an abstract class.

See that chapter for additional information on Test Doubles and search StackOverflow for more information on Mocking with PHPUnit


You are probably looking for mock objects.

http://www.phpunit.de/manual/3.6/en/test-doubles.html

https://github.com/padraic/mockery

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜