【发布时间】:2013-01-14 22:19:08
【问题描述】:
有没有办法用 PHPUnit 创建一个模拟类,然后我可以使用它的类名创建一个新实例?
我有一个定义两种方法的接口。比如:
interface FooInterface {
function getA();
function getB();
}
然后我有另一个类,它接受一个类名,创建该类的一个实例,检查它是否是它所期望的实例 (FooInterface),然后调用该类的两个方法来获取一些信息。
class FooInfo {
protected $a;
protected $b;
public function __construct($fooClass) {
$foo = new $fooClass;
if (!($foo instanceof FooInterface)) {
throw new \Exception();
}
$this->a = $foo->getA();
$this->b = $foo->getB();
}
}
我知道如何模拟一个对象就好了。问题是,由于这个类接受一个类名,而不是一个对象(它是根据需要创建给定类的实例的 Manager 的一部分),我不能使用普通的模拟对象。
我尝试制作一个模拟对象,然后使用该类名。它似乎可以很好地创建对象,甚至似乎具有我模拟出来的功能。但是,它似乎没有遵循我稍后设置的 will($this->returnValue('myValue')) 部分。
public function testConstruct()
{
$foo = $this->getMockForAbstractClass('Foo', array('getA', 'getB'));
$foo->expects($this->any())->method->('getA')->will($this->returnValue('a'));
$foo->expects($this->any())->method->('getB')->will($this->returnValue('b'));
$copyClass = get_class($foo);
$copy = new $copyClass();
// Passes
$this->assertTrue(method_exists($copy, 'getA');
// Fails, $copy->getA() returns null.
$this->assertEquals($copy->getA(), $foo->getA());
}
所以,它确实有被模拟的函数,但它们都返回 null。
有什么想法吗?
【问题讨论】:
标签: php unit-testing mocking phpunit