[英]PhpUnit when I use Mock Builder for Interface I get the correct class
I have the following class 我有以下课程
namespace MyApp;
use MyApp\SomeInterface;
class MyClass
{
public function __construct(SomeInterface $s)
{
//Some Logic here
}
//Another methods implemented There
}
The SomeInterface contains the following: SomeInterface包含以下内容:
namespace MyApp
interface SomeInterface
{
/**
* @return SomeObject
*/
public function someMethodToImpement();
}
And I want to create a mock over my phpunit Test Class: 我想在我的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);
}
}
But Once I run it I get the error: 但是一旦我运行它,我得到错误:
Tests\\MyApp\\MyClassTest::someTest TypeError: Argument 1 passed to MyApp\\MyClass::__construct() must implement interface MyApp\\SomeInterface, instance of PHPUnit\\Framework\\MockObject\\Builder\\InvocationMocker given, called in /home/vagrant/code/tests/MyApp/MyClassTest.php on line 测试\\ MyApp \\ MyClassTest :: someTest TypeError:传递给MyApp \\ MyClass :: __ construct()的参数1必须实现接口MyApp \\ SomeInterface,给出PHPUnit \\ Framework \\ MockObject \\ Builder \\ InvocationMocker的实例,在/ home / vagrant / code中调用/tests/MyApp/MyClassTest.php在线
Do you know why that happens and how actually will create the mock Interface? 你知道为什么会发生这种情况以及如何创建模拟接口吗?
Instead of constructing the mock via 而不是构建模拟通过
$mockInterface=$this->createMock(SomeInterface::class)
->method('someMethodToImpement')->will($this->returnValue($fakeClass));
Split it into seperate lines: 将其拆分为单独的行:
$mockInterface=$this->createMock(SomeInterface::class);
$mockInterface->method('someMethodToImpement')->will($this->returnValue($fakeClass));
And will work like a charm. 并将像魅力一样工作。
I've had a similar issue. 我有类似的问题。 I fixed it by adding those interfaces as another mock()
parameter 我通过将这些接口添加为另一个mock()
参数来修复它
class Product implements PriceInterface, ProductDataInterface {
// ...
}
Test: 测试:
// throws error
$product = Mockery::mock(Product::class);
// works fine
$product = Mockery::mock(Product::class, 'PriceInterface, ProductDataInterface');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.