unit-testing - PHPUnit - Setter 不修改我的模拟

标签 unit-testing symfony mocking phpunit

我使用 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 了 gettersetter 具有这样的功能

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

相关文章:

c# - 在 Asmx Web 服务单元测试中出错

mysql - 使用 Doctrine2 的一个很好的 SQL 查询,用于从标签列表中获取项目

java - 模拟Mvc。 VewResolver 工作后检查 url?

php - Doctrine2 和 Postgres : Invalid input syntax for boolean : ""

unit-testing - 如何访问 PHPUnit 模拟对象上的重载属性?

c# - 如何创建一个文件来填充 HttpContext.Current.Request.Files?

ios - Xcode 在单元测试中写入文件

objective-c - OCUnit 中的简化断言

Android Activity 单元测试中模拟数据源的技巧

php - Symfony 2 使用自定义反规范化器对嵌套对象进行反规范化