作者:倒退淂磁带_628 | 来源:互联网 | 2022-12-02 20:43
我有以下课程
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();
}
我想在我的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);
}
}
但是一旦我运行它,我得到错误:
Tests \ MyApp \ MyClassTest :: someTest TypeError:传递给MyApp \ MyClass :: __ construct()的参数1必须实现接口MyApp \ SomeInterface,PHPUnit \ Framework \ MockObject \ Builder \ InvocationMocker的实例已给出,在/ home / vagrant / code中调用/tests/MyApp/MyClassTest.php在线
您知道为什么会发生这种情况以及如何实际创建模拟接口吗?
1> Dimitrios De..:
而不是通过构造模拟
$mockInterface=$this->createMock(SomeInterface::class)
->method('someMethodToImpement')->will($this->returnValue($fakeClass));
将其分成单独的行:
$mockInterface=$this->createMock(SomeInterface::class);
$mockInterface->method('someMethodToImpement')->will($this->returnValue($fakeClass));
并且会像魅力一样工作。