定义的路线web.php
是
Route::get('about-us', [PageController::class, 'renderAboutUsPage'])->name('pages.about-us');
在我的控制器中,我有方法
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]);
}
}
我的理解是,当我测试该方法renderAboutUsPage()
时,我应该pageService->getActivePageBySlug($slug)
在测试中进行模拟,以避免真正调用该方法。这将有助于减少测试执行时间。
我对我的服务进行了单独的测试,并进行了getActivePageBySlug()
独立测试。
我的测试用例是
/**
* @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');
}
我不知道如何getActivePageBySlug($slug)
在我的测试用例中模拟该方法以避免真正的调用。
方法的定义getActivePageBySlug($slug)
是:
/**
* 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;
}
}