phpunitのドキュメントに続いて、私は次のコードを思いついた。テストは失敗し、出力はスタブされたメソッドを呼び出すのではなく、実際のメソッドであり、データベースに当たってデータベースからデータを返すことを示しています。私は実際のクラスメソッドの代わりに呼び出されるようにテストダミーを "注入"するステップがないと思います。誰でも私がここで間違っていることを指摘できますか?Laravel 5.3で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 =新しいCategoryClass;
CategoryClassのfindAllメソッド:
public function findAll() {
// List all categories
$categories = Category::all(); // Eloquent call to database.
return json_encode($categories);
}
おかげ億!
あなた自身が質問に答えてくれたと思います。「...私はテストダミーを注入するステップを逃しています...」 –
それでは、私は正しい道を進んでいますか?ドキュメントに追加の手順はありませんが、これは私の問題の分析です。このスタブを「注入」する必要がある場合は、どうすればそれをやりますか?これは、私が使用しているドキュメントです:https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.stubs –