[英]Mock controller in Symfony2 unit test
I am writing unit tests for an API Service in a Symfony2 project. 我正在为Symfony2项目中的API服务编写单元测试。 One service method takes a controller instance as an argument, and handles the requested JSON.
一种服务方法将控制器实例作为参数,并处理请求的JSON。
public function getJSONContent(Controller $controller) {
$version = $this->getAPIVersion();
//Read in request content
$content = $controller->get("request")->getContent();
if (empty($content)) {
throw new HttpException(400, 'Empty request payload');
}
//Parse and Detect invalid JSON
$jsonContent = json_decode($content, true);
if($jsonContent === null) {
throw new HttpException(400, 'Malformed JSON content received');
}
return $jsonContent;
}
The following is my test: 以下是我的测试:
class ApiTest extends \PHPUnit_Framework_TestCase {
public function testGetJSONContent() {
// Create a stub for the OrgController Object
$stub = $this->getMock('OrganizationController');
// Create the test JSON Content
$post = 'Testy Test';
$request = $post;
$version = "VersionTest";
$APIService = new APIService();
// Configure the Stub to respond to the get and getContent methods
$stub->expects($this->any())
->method('get')
->will($this->returnValue($post));
$stub->expects($this->any())
->method('getContent')
->will($this->returnValue($request));
$stub->expects($this->any())
->method('getAPIVersion')
->will($this->returnValue($version));
$this->assertEquals('Testy Test', $APIService->getJSONContent($stub));
}
}
My test throws the following error: 我的测试抛出以下错误:
Argument 1 passed to Main\\EntityBundle\\Service\\APIService::getJSONContent() must be an instance of Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller, instance of Mock_OrganizationController_767eac0e given. 传递给Main \\ EntityBundle \\ Service \\ APIService :: getJSONContent()的参数1必须是Symfony \\ Bundle \\ FrameworkBundle \\ Controller \\ Controller的实例,给出Mock_OrganizationController_767eac0e的实例。
My stub is obviously not fooling anyone, is there any way to fix this? 我的存根显然不是在欺骗任何人,有没有办法解决这个问题?
Use the namespace to specify the controller you are mocking. 使用命名空间指定要模拟的控制器。 Ie
即
// Create a stub for the OrgController Object
$stub = $this->getMock('Acme\AcmeBundle\Controller\OrganizationController');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.