模拟测试特征和模拟方法

Mockery test trait and mock method

我尝试用两种方法对特征进行单元测试。我想断言 foo 的结果,它调用了特征中的另一个方法:

<?php
trait Foo {
    public function foo() {
        return $this->anotherFoo();
    }

    public function anotherFoo() {
        return 'my value';
    }
}

/** @var MockInterface|Foo */
$mock = Mockery::mock(Foo::class);
$mock
    ->makePartial()
    ->shouldReceive('anotherFoo')
    ->once()
    ->andReturns('another value');

$this->assertEquals('another value', $mock->foo());

当我 运行 phpunit:

时得到以下结果
There was 1 failure:

1) XXX::testFoo
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'another value'
+'my value'

这样一般可以吗?

我不认为你可以直接模拟这样的特征。似乎有效的是做同样的事情,但使用使用特征的 class 。因此,例如,创建一个使用 Foo 的测试 Bar class,然后对 that 进行部分模拟。这样你就可以使用真实的 class 并且 Mockery 似乎很乐意覆盖 trait 方法。

trait Foo {
    public function foo() {
        return $this->anotherFoo();
    }

    public function anotherFoo() {
        return 'my value';
    }
}

class Bar {
    use Foo;
}

/** @var MockInterface|Bar */
$mock = Mockery::mock(Bar::class);
$mock
    ->makePartial()
    ->shouldReceive('anotherFoo')
    ->once()
    ->andReturns('another value');

$this->assertEquals('another value', $mock->foo());