Following the phpunit documentation, I have come up with the following code. The test fails and the output shows me that it is not calling the stubbed method, but the actual method, hitting the database and returning the data from the database. I believe I am missing a step where I "inject" the test dummy so that it is called instead of the actual class method. Can anyone point out what I am doing wrong here?
My Test :
$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 method:
public function index() {
// List all category
return $this->categoryClass->findAll();
}
Note: $this->categoryClass is being instantiated in the constructor method of CategoriesController. $this->categoryClass = new CategoryClass;
The findAll method of CategoryClass:
public function findAll() {
// List all categories
$categories = Category::all(); // Eloquent call to database.
return json_encode($categories);
}
Thanks a billion!