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

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

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

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

注意:此方法的调用 Facade::count('table_name') 应该 return 此 table 中的行数,即 Int.

我试过这个测试,它没有像我预期的那样 return Int return :

/**
 * @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 的静态方法?在这种情况下是否还有其他方法或技术可行?请指教。

谢谢。

我建议你使用The Phake mock testing library that support Mocking Static Methods。例如:

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

希望对您有所帮助