【问题标题】:Mockery test trait and mock method模拟测试特征和模拟方法
【发布时间】:2020-04-12 06:39:54
【问题描述】:

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

<?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'

这样一般可以吗?

【问题讨论】:

    标签: php unit-testing testing mockery


    【解决方案1】:

    我认为你不能直接嘲笑这样的特质。似乎可行的是做同样的事情,但使用一个使用该特征的类。因此,例如,创建一个使用Foo 的测试Bar 类,然后对that 进行部分模拟。这样你就可以使用一个真正的类,而 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());
    

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 2023-04-04
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      相关资源
      最近更新 更多