本文介绍了使用Mockery在PHP中模拟接口时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中使用Mockery模拟接口时遇到了一个问题(即使用laravel框架,但我不确定这是否相关.

I have run into a problem when mocking Interfaces using Mockery in PHP (im using the laravel framework but I'm not sure this is relevant.

我已经定义了一个接口

<?php namespace MyNamespace\SomeSubFolder;

interface MyInterface {

    public function method1();

}

我有一个类可以在一种方法上提示该接口...

And I have a class that typehints that interface on one of the methods...

<?php namespace MyNamespace\SomeSubFolder;

use MyNamespace\SomeSubFolder\MyInterface;

class MyClass {

    public function execute(MyInterface $interface)
    {
         //does some stuff here

    }
}

...并且我正在尝试测试MyClass.我创建了一个看起来像这样的测试:

...and I am trying to test MyClass. I have created a test that looks something like this:

public function testExecute()
{

    $mock = Mockery::mock('MyNamespace\SomeSubFolder\MyInterface');

    $mock->shouldReceive('method1')
         ->andReturn('foo');

    $myClass = new MyClass();

    $myClass->execute($mock);

}

运行测试时,我收到消息

When I run the test I receive the message

"ErrorException:传递给MyClass :: execute的参数1必须是MyNamespace \ SomeSubFolder \ MyInterface的实例,是给定的Mockery_123465456的实例...."

'ErrorException: Argument 1 passed to MyClass::execute must be an instance of MyNamespace\SomeSubFolder\MyInterface, instance of Mockery_123465456 given....'

我不知道为什么.

在测试中,我尝试了以下操作:

Within the test I have tried the following :

$this->assertTrue(interface_exists('MyNamespace\SomeSubFolder\MyInterface'));

$this->assertTrue($mock instanceof MyInterface);

都返回true,因此好像我已经创建了实现该接口的实例,但是当我在类上调用该方法时,它就不同意了.有什么想法吗?

and both return true, so it appears as if I have created and instance that implements the interface, but when I call the method on the class it disagrees. Any ideas???

推荐答案

您应该在模拟声明的和处调用mock()方法.

You should call mock() method at the and of mock declaration.

$mock = Mockery::mock('MyNamespace\SomeSubFolder\MyInterface');

$mock->shouldReceive('method1')
     ->andReturn('foo')
     ->mock();

这篇关于使用Mockery在PHP中模拟接口时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 09:20