The route defined in web.php is
Route::get('about-us', [PageController::class, 'renderAboutUsPage'])->name('pages.about-us');
In my controller, I have methods
class PageController extends Controller
{
protected $pageService;
/**
* Class contructor
*/
public function __construct(PageService $pageService)
{
$this->pageService = $pageService;
}
/**
* Method to render about us page
*/
public function renderAboutUsPage(){
return $this->renderStaticPage('about-us');
}
/**
* Method to render static page
* @param slug
*/
private function renderStaticPage($slug) {
Log::info("Rendering ".$slug." static page.");
$page = $this->pageService->getActivePageBySlug($slug);
return view('pages.static-page', ['data'=>$page]);
}
}
What my understanding says when I test the method renderAboutUsPage() then I should mock pageService->getActivePageBySlug($slug) in my test so that a real call to this method can be avoided. it will help reducing the test execution time.
I have separate tests for my service where I am testing getActivePageBySlug() independently.
My test case is
/**
* @test
* @testdox Whether the about us page returns a successful response, renders the correct view, contains view object {data} and log correct messages in log file.
* @group website
* @group static-pages
*/
public function test_whether_about_us_page_renders_successfully()
{
Log::shouldReceive('info')->once()->with("Rendering about-us static page.");
Log::shouldReceive('info')->once()->with("Getting page by active status and provided slug.");
$response = $this->get('about-us');
$response->assertStatus(200);
$response->assertViewIs('pages.static-page');
$response->assertViewHas('data');
}
I do not know how to mock the method getActivePageBySlug($slug) in my test case to avoid real call.
The definition of getActivePageBySlug($slug) method is:
/**
* Method to get page by slug (Checks to page status is active)
* @param string slug
* @return Page page
* @throws Throwable e
*/
public function getActivePageBySlug(string $slug)
{
Log::info("Getting page by active status and provided slug.");
try
{
$page = Page::where('slug',$slug)->where('status', Status::active->value())->first();
if(!$page) {
throw new NotFoundHttpException("The page ". $slug ." not found.");
}
return $page;
}
catch (Throwable $e)
{
Log::error("Error in getting page by slug.");
throw $e;
}
}