PHPUnit模型问题
PHPUnit Mockup issue
我有一个服务模型 class。
在我的setUp
函数
中是这样定义的
$this->myServiceMockup = $this->getMockBuilder(MyService::class)
->disableOriginalConstructor()
->setMethods(['myMethod'])
->getMock();
在我的测试函数中,我设置了这样的期望值。
$this->myServiceMockup->expects($this->once())
->method('myMethod')
->with($this->exactly(1), 'myName')
->willReturn($this->exactly(1));
所以这意味着当我应该只触发一次 myMethod 函数并且它将 return 整数 1.
所以我正在测试的方法有那行代码。
$myIntValue = $this->myService->myMethod($number, $name);
在这一行之后 $myIntValue
当我 运行 测试应该是 1 并且测试应该继续,这就是我对此的理解。
但是我得到了这个错误
Expectation failed for method name is equal to when
invoked 1 time(s) Parameter 0 for invocation
My\Path\To\Class\MyService::myMethod(1, 'myName') does not match
expected value.
1 does not match expected type "object".
没有任何意义,因为 myMethod
需要一个整数和一个字符串。
public function myMethod($number, $name)
{
return $this->table->save($number, $name);
}
有人可以向我解释我在这里做错了什么,因为我没有想法。
exactly()
是调用计数匹配器(如 once()
或 any()
),用作 expects()
方法的参数。
只需更换:
->with($this->exactly(1), 'myName')
到
->with(1, 'myName')
willReturn()
也接受值 "as is"。
您没有正确使用 $this->with
。
$this->myServiceMockup
->expects($this->once())
->method('myMethod')
->with($this->equalTo(1), $this->stringContains('myName'))
->willReturn(1);
我有一个服务模型 class。
在我的setUp
函数
$this->myServiceMockup = $this->getMockBuilder(MyService::class)
->disableOriginalConstructor()
->setMethods(['myMethod'])
->getMock();
在我的测试函数中,我设置了这样的期望值。
$this->myServiceMockup->expects($this->once())
->method('myMethod')
->with($this->exactly(1), 'myName')
->willReturn($this->exactly(1));
所以这意味着当我应该只触发一次 myMethod 函数并且它将 return 整数 1.
所以我正在测试的方法有那行代码。
$myIntValue = $this->myService->myMethod($number, $name);
在这一行之后 $myIntValue
当我 运行 测试应该是 1 并且测试应该继续,这就是我对此的理解。
但是我得到了这个错误
Expectation failed for method name is equal to when invoked 1 time(s) Parameter 0 for invocation
My\Path\To\Class\MyService::myMethod(1, 'myName') does not match expected value.
1 does not match expected type "object".
没有任何意义,因为 myMethod
需要一个整数和一个字符串。
public function myMethod($number, $name)
{
return $this->table->save($number, $name);
}
有人可以向我解释我在这里做错了什么,因为我没有想法。
exactly()
是调用计数匹配器(如 once()
或 any()
),用作 expects()
方法的参数。
只需更换:
->with($this->exactly(1), 'myName')
到
->with(1, 'myName')
willReturn()
也接受值 "as is"。
您没有正确使用 $this->with
。
$this->myServiceMockup
->expects($this->once())
->method('myMethod')
->with($this->equalTo(1), $this->stringContains('myName'))
->willReturn(1);