代码之家  ›  专栏  ›  技术社区  ›  Dimitrios Desyllas

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

  •  1
  • Dimitrios Desyllas  · 技术社区  · 6 年前

    我有以下课程

    namespace MyApp;
    
    use MyApp\SomeInterface;
    
    class MyClass
    {
      public function __construct(SomeInterface $s)
      {
        //Some Logic here
      }
    
      //Another methods implemented There
    }
    

    SomeInterface包含以下内容:

    namespace MyApp
    
    interface SomeInterface
    {
      /**
      * @return SomeObject
      */
      public function someMethodToImpement();
    }
    

    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);
       }
    }
    

    但一旦我运行它,我就会得到一个错误:

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

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

    2 回复  |  直到 6 年前
        1
  •  26
  •   Dimitrios Desyllas    6 年前

    而不是构造模拟通孔

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

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

    会很有魅力的。

        2
  •  1
  •   WellBloud    6 年前

    我也遇到过类似的问题。我通过将这些接口添加为另一个接口来修复它 mock()

    class Product implements PriceInterface, ProductDataInterface {
        // ...
    }
    

    测试:

    // throws error
    $product = Mockery::mock(Product::class);
    // works fine
    $product = Mockery::mock(Product::class, 'PriceInterface, ProductDataInterface');
    

    Link to documentation

    推荐文章