我使用 PHPUnit 进行单元测试(Symfony2 应用程序)。
这是我要测试的方法(简化):
public function __construct(Email $email)
{
$this->email = $email;
}
public function sendEmail()
{
// Here, more logic and condition, it's simplified
if ($this->email->getOk() === 1) {
$this->email->setSendEmail(1);
}
return $this->email;
}
还有我的测试:
$emailMock = $this->getMock(Email::class);
$emailMock->method('getOk')->will($this->returnValue(1));
$emailMock->method('setSendEmail')->will($this->returnArgument(0));
$email = new Email($emailMock);
$emailModified = $email->sendEmail();
var_dump($emailModified->getSendEmail()); // Returns NULL
我的类(class)电子邮件是一个 Doctrine 实体(setter 和 getter 在里面)(an example of entity)
我如何测试我的模拟是否被我的类(class)补充水分? 我想通过查看我的对象是否水化来了解我的方法是否有效。
编辑
我尝试另一种方法:
$object = $this->getMock(MyClass::class);
$object->method('setPosition')->will(
$this->returnCallback(
$pos = function ($arg) {
return $arg;
}
)
);
$object->method('getPosition')->will($this->returnValue($pos));
$method = new \ReflectionMethod(MyClass::class, 'testMethod');
$method->setAccessible(true);
$res = $method->invoke(new MyClass($object));
var_dump($res->getPosition()) // Return inexploitable Closure
我希望 $object->getPosition()
在我执行 $object->setPosition(1)
时返回 1
我测试的外部类 MyClass()。
最佳答案
迟到的答案,但我最终 mock 了 getter
和 setter
具有这样的功能
// Mock setter
$exceptionEvent->expects($this->once())->method('setResponse')->willReturnCallback(
function($arg) use ($exceptionEvent) {
$exceptionEvent->response = $arg;
}
);
// Mock getter
$exceptionEvent->expects($this->once())->method('getResponse')->willReturnCallback(
function() use ($exceptionEvent) {
return $exceptionEvent->response;
}
);
我正在测试的类接受 $exceptionEvent
并对其调用 setResponse()
。这个解决方案对我有用,然后我在通过所述类运行它之后对 $exceptionEvent->getResponse()
进行断言。
关于unit-testing - PHPUnit - Setter 不修改我的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35848835/