用RedBeanPHP ORM对业务逻辑进行单元测试的正确方法是什么?


what is the right way to Unit test business logic with RedBeanPHP ORM

我想测试与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);
}

是否有办法模拟红豆的静态方法?如果有其他的方法或技术可能在这种情况下起作用?请告知。

谢谢。

我建议您使用支持mock静态方法的Phake模拟测试库。为例:

/**
 * @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'));
}

希望对您有所帮助