【问题标题】:Mocking a method within tested class在测试类中模拟方法
【发布时间】:2015-10-01 02:42:05
【问题描述】:

我正在使用 PHPUnit 4.6.4

我很难理解如何在测试类中模拟方法,我在网上查看了一些其他示例,但似乎不起作用。

我在 Auth 类中有以下函数

    public function check_that_user_is_admin() {
        if ($this->get_user_role() !== '1') {
            // only admin allowed to perform this action
            return FALSE;
        }

        return TRUE;
    }

'get_user_role' 检查活动会话以查看当前用户拥有的用户级别并返回其值。

这是对上面函数的测试

    public function testAuth() {
            $mock = $this->getMockBuilder('Auth')->disableOriginalConstructor()->getMock(array('get_user_role'));
            $mock->expects($this->once())->method('get_user_role')->with($this->returnValue(1));

            $this->assertTrue($mock->check_that_user_is_admin());
    }

每次运行测试时,我都会收到: '断言 null 为真失败。'

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

    我碰巧找到了答案……

        $mock = $this->getMockBuilder('Auth')
            ->disableOriginalConstructor()
            ->setMethods(array('get_user_role'))
            ->getMock();
    
        $mock->expects($this->once())
            ->method('get_user_role')
            ->willReturn("2");
    
        $this->assertFalse($mock->check_that_user_is_admin());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      相关资源
      最近更新 更多