工厂本质上是可测试的,您只是试图对实现进行过于严格的控制。
您将检查是否通过以下方式获得了类的实例$this->assertInstanceOf()
。然后,对于生成的对象,您将确保属性设置正确。为此,您可以使用任何公共访问器方法或使用$this->assertAttribute*
PHPUnit 中可用的方法。
http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.assertions.assertEquals http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.assertions.assertEquals
许多常见断言还能够检查受保护属性和私有属性的属性。
我不会在参数列表中指定类名,因为您的用法是工厂仅返回一种类型,并且仅更改依赖项。让它返回模拟对象类型是不必要的,并且会使您的测试更加复杂。
测试最终看起来像这样:
public function testBuild() {
$factory = new MyBuilder();
//I would likely put the following into a data provider
$param1 = 'foo';
$param2 = 'bar';
$depen1 = 'boo';
$depen2 = 'baz';
$depen3 = 'boz';
$object = $factory->build($param1, $param2);
$this->assertInstanceOf('MyClass', $object);
//Check the object definition
//This would change depending on your actual implementation of your class
$this->assertAttributeEquals($depen1, 'attr1', $object);
$this->assertAttributeEquals($depen2, 'attr2', $object);
$this->assertAttributeEquals($depen3, 'attr3', $object);
}
您现在要确保您的工厂返回正确的对象。首先确保它是正确的类型。然后确保它已正确初始化。
你依赖于MyClass
为了通过测试,但这并不是一件坏事。您的工厂旨在创建MyClass
对象,因此如果该类未定义,那么您的测试肯定会失败。
在开发过程中测试失败也不是一件坏事。