当我将Mock Builder用于接口时,PhpUnit得到了正确的类

Dim*_*las 2 php phpunit mocking

我有以下课程

namespace MyApp;

use MyApp\SomeInterface;

class MyClass
{
  public function __construct(SomeInterface $s)
  {
    //Some Logic here
  }

  //Another methods implemented There
}
Run Code Online (Sandbox Code Playgroud)

SomeInterface包含以下内容:

namespace MyApp

interface SomeInterface
{
  /**
  * @return SomeObject
  */
  public function someMethodToImpement();
}
Run Code Online (Sandbox Code Playgroud)

我想在我的phpunit测试类上创建一个模拟:

namespace Tests\MyApp;

use PHPUnit\Framework\TestCase;
use MyApp\MyClass;
use MyApp\SomeInterface;

class MyClassTest extends TestCase
{
   public function someTest()
   {

     $fakeClass=new class{
          public function myFunction($arg1,$arg2)
          {
            //Dummy logic to test if called
            return $arg1+$arg2;
          }
     };

     $mockInterface=$this->createMock(SomeInterface::class)
      ->method('someMethodToImpement')
      ->will($this->returnValue($fakeClass));

     $myActualObject=new MyClass($mockInterface);
   }
}
Run Code Online (Sandbox Code Playgroud)

但是一旦我运行它,我得到错误:

Tests \ MyApp \ MyClassTest :: someTest TypeError:传递给MyApp \ MyClass :: __ construct()的参数1必须实现接口MyApp \ SomeInterface,PHPUnit \ Framework \ MockObject \ Builder \ InvocationMocker的实例已给出,在/ home / vagrant / code中调用/tests/MyApp/MyClassTest.php在线

您知道为什么会发生这种情况以及如何实际创建模拟接口吗?

Dim*_*las 9

而不是通过构造模拟

 $mockInterface=$this->createMock(SomeInterface::class)
      ->method('someMethodToImpement')->will($this->returnValue($fakeClass));
Run Code Online (Sandbox Code Playgroud)

将其分成单独的行:

 $mockInterface=$this->createMock(SomeInterface::class);
 $mockInterface->method('someMethodToImpement')->will($this->returnValue($fakeClass));
Run Code Online (Sandbox Code Playgroud)

并且会像魅力一样工作。

  • 谢谢,这对我有用!在我看来,在答案中值得一提(我建议您附加它),其原因是“method()”和“will()”方法返回调用模拟实例,而“createMock()”返回模拟本身,实际上必须传递给 sut(sut - 被测系统) (2认同)