php - 我如何模拟一个应该接受数组的方法?

标签 php unit-testing testing phpunit shopware

我是 PHPUnit 测试的新手,我想做的是测试一个名为 returnOnLogin() 的方法,该方法接受参数 Enlight_Event_EventArgs $args 并返回

这是我要测试的方法:

public function returnOnLogin(\Enlight_Event_EventArgs $args)
{
    $controller = $args->get('subject');
    $view = $controller->View();

    $controller->redirect([
        'controller' => 'verification'
    ]);

    // $view->addTemplateDir(
    // __DIR__ . '/Views'
    // );

    return true;
}

这是我的测试:

class MyFirstTestPluginTest extends TestCase
{
    public function testReturnOnLogin()
    {
        $my_plugin = new MyFirstTestPlugin(true);
        $expected = true;

       //I tried following but it did not work
       $this->assertEquals($expected, $my_plugin->returnOnLogin(//here is the problem it requires this array that I dont know));
   }

最佳答案

假设你的 Controller 类是Controller,并且假设我们不关心$controller中调用了view(),这应该涵盖您正在寻找的内容:

class MyFirstTestPluginTest extends TestCase
{
    public function testReturnOnLogin()
    {
        /**
         * create a test double for the controller (adjust to your controller class)
         */
        $controller = $this->createMock(Controller::class);

        /**
         * expect that a method redirect() is called with specific arguments
         */
        $controller
            ->expects($this->once())
            ->method('redirect')
            ->with($this->identicalTo([
                'controller' => 'verification'
            ]));

        /**
         * create a test double for the arguments passed to returnLogin()
         */
        $args = $this->createMock(\Enlight_Event_EventArgs::class);

        /** 
         * expect that a method subject() is invoked and return the controller from it
         */
        $args
            ->expects($this->once())
            ->method('subject')
            ->willReturn($controller);

        $plugin = new MyFirstTestPlugin(true);

        $this->assertTrue($plugin->returnOnLogin($args));
    }
}

这个测试是做什么的?

安排

此测试首先安排测试替身以用于被测系统(您的插件)。

第一个测试替身是你的 Controller ,我们以这样的方式设置它,即我们期望使用与指定数组相同的参数调用一次方法 redirect()

第二个测试替身是参数,我们以这样一种方式设置它,即我们期望方法“subject()”被调用,并将返回 Controller 。

然后,我们设置被测系统,只需创建一个 MyFirstTestPlugin 实例,将 true 传递给构造函数即可。

很遗憾,您没有与我们分享构造函数,我们不知道参数 true 代表什么。如果它影响 returnLogin() 的行为,那么我们显然需要添加更多测试来断言参数采用不同值时的行为。

行动

然后此测试调用被测系统上的方法 returnLogin(),并传入其中一个测试替身。

断言

最终,此测试断言方法 returnLogin() 返回 true

注意看看

关于php - 我如何模拟一个应该接受数组的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037964/

相关文章:

php - 我如何在 ZF 中编写此查询?

unit-testing - 如何使用 isparta、webpack、jasmine 和 karma 获得准确的代码覆盖率数字?

java - 我正在尝试为插入时间表的方法编写一个 JUnit 测试用例,该时间表将参数作为员工 ID。我应该如何尝试?

testing - 我如何使用 Cabal 设置一个简单的测试?

php - PHP 中是否可以防止 "Fatal error: Call to undefined function"?

php - XPATH 检查属性是否包含多个值之一

javascript - 如何使用 JavaScript 和 jQuery 存储数据

visual-studio - VS 2008,分析多个测试

java - 通过 JDBC 使用 JUnit 测试来测试 SQL 有什么问题吗?

selenium - Selenide 中的 System.setProperty 和 Configuration.browser 有什么区别?