【发布时间】:2019-03-11 17:17:15
【问题描述】:
我有以下课程
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 中调用上线
您知道为什么会发生这种情况以及实际将如何创建模拟接口吗?
【问题讨论】: