【发布时间】:2017-03-09 01:02:55
【问题描述】:
按照 phpunit 文档,我想出了以下代码。测试失败,输出显示它不是调用存根方法,而是实际方法,访问数据库并从数据库返回数据。我相信我错过了“注入”测试虚拟对象的步骤,以便调用它而不是实际的类方法。谁能指出我在这里做错了什么?
我的测试:
$shouldReturn = '[{"name":"A Category Name 1"},{"name":"A Category Name 2"},{"name":"A Category Name 3"}]';
// Create a mock for the CategoryClass,
$catClassMock = $this->getMockBuilder(CategoryClass::class)->getMock();
// Set up the Test Dummy for the findAll method and stub what should be returned.
$catClassMock->expects($this->once())
->method('findAll')
->with($this->returnValue($shouldReturn));
// Setup the controller object, and call the index method.
$CategoriesController = new CategoriesController();
$returnedResults = $CategoriesController->index();
// Assert the results equal what we told the method to return.
$this->assertEquals($returnedResults, $shouldReturn);
CategoriesController 方法:
public function index() {
// List all category
return $this->categoryClass->findAll();
}
注意:$this->categoryClass 是在 CategoriesController 的构造方法中实例化的。 $this->categoryClass = new CategoryClass;
CategoryClass的findAll方法:
public function findAll() {
// List all categories
$categories = Category::all(); // Eloquent call to database.
return json_encode($categories);
}
感谢十亿!
【问题讨论】:
-
我想你自己回答了这个问题:“......我错过了一个“注入”测试假人的步骤......”
-
那么我走对了吗?文档中没有任何额外的步骤,这只是我对问题的分析。如果我确实需要“注入”这个存根,我该怎么做呢?这是我正在使用的文档:phpunit.de/manual/current/en/…