【问题标题】:How test methods that are not of my test class with PHPUnit, mock, stub如何使用 PHPUnit、mock、stub 测试不属于我的测试类的方法
【发布时间】:2017-10-20 02:45:42
【问题描述】:

我有这门课

<?php 

class Password 
{
    protected function checkPassword()
    {
        $this->callExit();
    }

    protected function callExit()
    {
    exit;
    }    
}

这是我的测试:

 public function testAuthorizeExitsWhenPasswordNotSet()
    {


        $badCode = $this->getMockBuilder(Password::class)
            ->setMethods(array('callExit'))
            ->getMock();

        $badCode->expects($this->once())
            ->method('callExit');

        $badCode->checkPassword();

    }

在早期的类中,callExit 方法属于 Password 类。 我的问题是,我可以测试不属于 Password 类的方法吗?

例如在checkPassword方法中:

protected function checkPassword()
{
    $user = new User;

    $this->callExit();

    $user->fillOut();

}

我想为fillOut 方法做一个模拟,我该怎么做?

帮帮我!!

【问题讨论】:

  • 创建 mocker 用户类并使用该 mock 对象调用 fillout()
  • 我想检查fillOut方法是否在checkPassword方法@zod内部被调用

标签: php unit-testing testing mocking phpunit


【解决方案1】:

根据您的代码编写方式,您无法模拟 fillOut 方法,因为您在要测试的方法中实例化 User 对象。没有办法用这样的模拟替换对象。

为了测试这个方法,你应该将一个User 对象传递给checkPassword 方法。然后,您将能够创建一个 MockUser 并模拟 fillOut 方法。

所以你的方法应该是这样的:

protected function checkPassword(User $user) {
    $this->callExit();
    $user->fillOut();
}

在您发布的代码中,您正在调用 exit()。请记住,如果执行此操作,它也会停止 PHPUnit。

您还试图显式测试受保护的方法,您真的不应该这样做。你应该只测试你的类的公共方法。在测试公共方法时,应执行受保护和私有方法。这使您可以重构类的内部结构并知道您没有更改类的功能。

如果您觉得需要显式测试受保护的函数,这表明您应该将该方法移到一个单独的类中,该类将提供给您正在测试的对象。

【讨论】:

    猜你喜欢
    • 2014-02-08
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 2014-07-06
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    相关资源
    最近更新 更多