使用闭包的PHPUnit测试 [英] PHPUnit testing with closures

查看:117
本文介绍了使用闭包的PHPUnit测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这试图为一个类的方法编写一个测试,该方法调用了一个带有闭包的mock方法。你将如何验证被调用的闭包?

This came up trying to write a test for a method of a class that calls a mock method with a closure. How would you verify the closure being called?

我知道你可以断言该参数是 Closure

I know that you would be able to assert that the parameter is an instance of Closure. But how would you check anything about the closure?

例如,如何验证传递的函数:

For example how would you verify the function that is passed:

 class SUT {
     public function foo($bar) {
         $someFunction = function() { echo "I am an anonymous function"; };
         $bar->baz($someFunction);
     }
 }

 class SUTTest extends PHPUnit_Framework_TestCase {
     public function testFoo() {
         $mockBar = $this->getMockBuilder('Bar')
              ->setMethods(array('baz'))
              ->getMock();
         $mockBar->expects($this->once())
              ->method('baz')
              ->with( /** WHAT WOULD I ASSERT HERE? **/);

         $sut = new SUT();

         $sut->foo($mockBar);
     }
 }

您不能在PHP中比较两个闭包。在PHPUnit中有一种方法来执行传入的参数或以某种方式验证它?

You can't compare two closures in PHP. Is there a way in PHPUnit to execute the parameter passed in or in some way verify it?

推荐答案

将闭包插入到 SUT中:注入你的依赖(闭包),这使得单元测试更加困难, :foo()而不是在里面创建它,你会发现测试更容易。

Inject the closure into SUT::foo() instead of creating it inside there and you'll find testing much easier.

请记住我对你的真实代码一无所知,所以这对你来说可能是不切实际的):

Here is how I would design the method (bearing in mind that I know nothing about your real code, so this may or may not be practical for you):

class SUT 
{
    public function foo($bar, $someFunction) 
    {
        $bar->baz($someFunction);
    }
}

class SUTTest extends PHPUnit_Framework_TestCase 
{
    public function testFoo() 
    {
        $someFunction = function() {};

        $mockBar = $this->getMockBuilder('Bar')
             ->setMethods(array('baz'))
             ->getMock();
        $mockBar->expects($this->once())
             ->method('baz')
             ->with($someFunction);

        $sut = new SUT();

        $sut->foo($mockBar, $someFunction);
    }
}

这篇关于使用闭包的PHPUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆