phplaravelunit-testingphpunitlaravel-unit-test

laravel unit testing error 'call to member function call() on null'


I want to write a unit test for a form post request.

public function addForm(SaveFormRequest $request)
{
    $this->servicelayer->addFormDetails($request->validated());

    return redirect->route('register');
}

How can I mock $request->validated(); for a FormRequest class.

I trying below like

$saveRequest = $this->createMock(SaveFormRequest::class);

But I got an error:

Error: call to a member function call() on null.

Thanks in advance.


Solution

  • It is really easy, you just don't mock a FormRequest. You have to do a Feature test instead, using $this->get or $this->post or whatever action you need.

    So you just pass the right parameters to your route so FormRequest literally passes the validation. This is the only way of testing this.

    If you explain why you want to do it this way, I could expand my answer, because I have no idea why you want to do it this way...