我有一个类的问题,它返回不可预测的值和单元测试调用该函数的方法。我要改变方法的返回值
我不能模拟这个方法,因为我不能创建实例。下面是一个例子:
// Class called MyClass
public function doSomething(){
$foo = new Foo();
$bar = $foo->getSomethingUnpredictable();
// Doing something with $bar and saves the result in $foobar.
// The result is predictable if I know what $foo is.
return $forbar;
}
// The test class
public function testDoSomething{
$myClass = new MyClass();
when("Foo::getSomethingUnpredictable()")->thenReturns("Foo");
// Foo::testDoSomething is now predictable and I am able to create a assertEquals
$this->assertEquals("fOO", $this->doSomething());
}
我可能会检查Foo::testDoSomething在单元测试中返回什么,然后计算结果,但是testDoSomething与doSomething只有很少的区别。我也不能检查其他值会发生什么。
doSomething不能有任何参数,因为使用了可变参数(所以我不能添加最佳参数)。
这就是为什么硬连线依赖是坏的,在其当前状态doSomething
是不可测试的。你应该这样重构MyClass
:
public function setFoo(Foo $foo)
{
$this->foo = $foo;
}
public function getFoo()
{
if ($this->foo === null) {
$this->foo = new Foo();
}
return $this->foo;
}
public function doSomething(){
$foo = $this->getFoo();
$bar = $foo->getSomethingUnpredictable();
// Doing something with $bar and saves the result in $foobar.
// The result is predictable if I know what $foo is.
return $forbar;
}
然后你将能够注入你的模拟Foo
实例:
$myClass->setFoo($mock);
$actualResult = $myClass->doSomething();
至于如何存根方法,这取决于您的测试框架。因为这个(when("Foo::getSomethingUnpredictable()")->thenReturns("Foo");
)不是PHPUnit