PhpUnit当我为接口使用Mock Builder时,我得到了正确的类
我有以下课程PhpUnit当我为接口使用Mock Builder时,我得到了正确的类,php,mocking,phpunit,Php,Mocking,Phpunit,我有以下课程 namespace MyApp; use MyApp\SomeInterface; class MyClass { public function __construct(SomeInterface $s) { //Some Logic here } //Another methods implemented There } SomeInterface包含以下内容: namespace MyApp interface SomeInterface {
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中在线调用
您知道为什么会发生这种情况,以及实际将如何创建模拟接口吗?而不是构建模拟通道
$mockInterface=$this->createMock(SomeInterface::class)
->method('someMethodToImpement')->will($this->returnValue($fakeClass));
将其拆分为单独的行:
$mockInterface=$this->createMock(SomeInterface::class);
$mockInterface->method('someMethodToImpement')->will($this->returnValue($fakeClass));
而且会很有魅力。我也遇到过类似的问题。我通过将这些接口添加为另一个
mock()
参数来修复它
class Product implements PriceInterface, ProductDataInterface {
// ...
}
测试:
thx,这对我很有用!在我看来,在回答中值得一提的是(我建议您附加它),原因是
method()
和will()
方法返回调用mocker实例,而createMock()
返回mock本身,实际上必须传递给sut(sut-测试中的系统)这种重新安排有什么不同…?第二次在这里已经跌跌撞撞了xD如何再投一票?
// throws error
$product = Mockery::mock(Product::class);
// works fine
$product = Mockery::mock(Product::class, 'PriceInterface, ProductDataInterface');