我正在尝试在Zend Framework 2.3中的控制器上运行测试。
我的测试动作如下:
public function listAction() {
// optional filtering
$filter = $this->params('filter'); // filter type
// params from JSON
$jsonPost = $this->getRequest()->getContent();
$params = json_decode($jsonPost);
$param1 = isset($params->query1) ? $params->query1 : NULL;
$param2 = isset($params->query2) ? $params->query2 : NULL;
$json = Array( // json container
'status' => TRUE,
'data' => Array(),
);
try {
// get data from Model
$list = new Mapping\Books\Listing();
if( !empty($filter)) { // optional filtering
$list->addFilter($filter, $param1, $param2);
}
$data = $list->setOrder()->getList();
// final data mapping to JSON and formating
foreach($data as $isbn => $book) {
$json['data'][$isbn] = Array(
'ISBN' => $book->getISBN(),
'title' => $book->getTitle(),
'rating' => $book->getRating(),
'release_date' => $book->getReleaseDate()->format('F Y'),
'authors' => Array() // multiple
);
// final authors mapping
foreach($book->getAuthors() as $author) {
$json['data'][$isbn]['authors'][] = Array(
'author_id' => $author->getId(),
'author_name' => $author->getName()
);
}
}
} catch(Exception $e) {
$json = Array(
'status' => FALSE,
'error' => $e->getMessage()
);
}
return new JsonModel( $json );
}
我的测试方法如下:
public function testListActionWithoutParams()
{
// object mocking
$listingMock = $this->getMockBuilder('Books\Model\Mapping\Books\Listing')
->disableOriginalConstructor()
->setMethods(Array('getData', 'setOrder'))
->getMock();
$listingMock->expects($this->once())->method('setOrder')
->will($this->returnSelf());
$listingMock->expects($this->once())->method('getData')
->willReturn( Array() ); // for testing is enough
$serviceManager = $this->getApplicationServiceLocator();
$serviceManager->setAllowOverride(true);
$serviceManager->setService('Books\Model\Mapping\Books\Listing', $listingMock);
// dispatch
$this->dispatch('/books');
// routing tests
$this->assertResponseStatusCode(200);
$this->assertModuleName('Books');
$this->assertControllerName('Books\Controller\Index');
$this->assertControllerClass('IndexController');
$this->assertActionName('list');
$this->assertMatchedRouteName('list');
// header tests
$this->assertResponseHeaderContains('Content-type', 'application/json; charset=utf-8');
}
我想我在这里想念一些东西。我的理解是,serviceManager也会“通知”自动加载器,实际上被调用的类应该被mock对象替换,但事实并非如此。
如何用mocked替换我的对象?
答案 0 :(得分:0)
首先,你的控制器有很多逻辑,不正确。
其次,我只能给你代码的工作流程:
在你的控制器中,你需要一个方法,它将返回列表对象,所以在行中:
// get data from Model
$list = new Mapping\Books\Listing();
应该是新方法调用:
// get data from Model
$list = $this->getListing();
方法:
public function getListing()
{
return new Mapping\Books\Listing();
}
现在你需要在控制器中模拟这个方法。而模拟方法返回的对象应该是你的模拟Mapping\Books\Listing
对象。