【问题标题】:what is the right way to Unit test business logic with RedBeanPHP ORM使用 RedBeanPHP ORM 对业务逻辑进行单元测试的正确方法是什么
【发布时间】:2017-02-23 17:31:00
【问题描述】:

我正在尝试测试与 RedBeanPHP ORM 交互的业务逻辑,我不想测试 RedBeanPHP 本身,而是测试与 RedBean 关联时我的代码的行为。

我想模拟我想测试的方法然后返回我需要的值,这样我就隔离了数据库连接,因为我不需要它,我只是测试该方法的行为......问题但是,RedBean 的所有方法都是公共静态的,我已经读过我不能模拟这些方法。

注意:这个方法Facade::count('table_name')的调用应该返回这个表的行数,也就是Int。

我尝试了这个测试,但它没有像我预期的那样返回 Int :

/**
 * @param string $tableName
 * @param int $returnValue
 *
 * @return \PHPUnit_Framework_MockObject_Builder_InvocationMocker
 */
protected function mockCount($tableName, $returnValue)
{
    $this->beanCount = $this->getMockBuilder(Facade::class)->setMethods(['count'])->getMock();
    return $this->beanCount
        ->expects($this->once())
        ->method('count')
        ->with($this->equalTo($tableName))
        ->willReturn($returnValue);
}

public function testCountSuccess()
{
    $tableCount = $this->mockCount('questions', 7);
    $this->assertInternalType('int', $tableCount);
}

有没有办法模拟 RedBean 的静态方法?并且在这种情况下是否有另一种方法或技术可能有效?请指教。

谢谢。

【问题讨论】:

    标签: php static mocking phpunit redbean


    【解决方案1】:

    我建议你使用支持Mocking Static MethodsThe Phake mock testing library。例如:

    /**
     * @param string $tableName
     * @param int $returnValue
     *
     * @return \PHPUnit_Framework_MockObject_Builder_InvocationMocker|Facade
     */
    protected function mockCount($tableName, $returnValue)
    {
        $this->beanCount = \Phake::mock(Facade::class);
    
        \Phake::whenStatic($this->beanCount)
            ->count($tableName)
            ->thenReturn($returnValue);
    
        return $this->beanCount;
    }
    
    public function testCountSuccess()
    {
        $tableCount = $this->mockCount('questions', 7);
        $this->assertEquals(7, $tableCount::count('questions'));
    }
    

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2014-03-04
      • 2013-07-27
      • 2022-01-06
      相关资源
      最近更新 更多