4

Okay so, I've tried searching for a while now for solutions on how and why this is happening, here it goes.

On production environment, this chunk of code works just fine.

public function store(Add $request) {
        $data = $request->validated();
        //....  some other stuff
}

Add is a class that extends Illuminate\Foundation\Http\FormRequest, it has some rules only (that I've checked and doesn't influence the error, being the reason for not being posted)

On my test schema, I've got a couple scenarios, mostly Acceptence tests to make sure everything is created (or not) according to different data input. These make calls such as $this->call($uri, $body, $headers) and they work as expected, simulating the production environment.

However, I'm trying to write a test specific to the Controller and it keeps on giving me this error:

$userController = new UserController();
$request = Add::create('/test', 'POST', $body);
$userController->store($request);

This outputs an error:

 Error: Call to a member function validated() on null
 vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php:188

I've tried to output what dd($request->validated()); returns but this is where it crashes.

  1. What is the solution?
  2. Why it happens?
abr
  • 2,071
  • 22
  • 38
  • `$this->call($uri, $body, $headers)` The second parameter is the `$body` but you are passing the method of the form in `Add::create('/test', 'POST', $body);`. Maybe this could be the issue? – Saiyan Prince Jun 18 '20 at 12:02
  • $this->call is a laravel testcase function to call URIs with http, Add::create is a class derivant of FormRequest that represents the body of a HTTP request, they're different things – abr Jun 18 '20 at 13:23

1 Answers1

0

When creating a new instance of the request there are some properties set to null, you will have to populate the container, redirector and validator yourself before you can use the request properly in the controller.

Something like this should work:

$userController = new UserController();

// create the request and set the container and redirector
$request = Add::create('/test', 'POST', $body)
    ->setContainer($this->app)
    ->setRedirector($this->app['redirect']);

// resolve the validator
$request->validateResolved();

$userController->store($request);
Remul
  • 7,874
  • 1
  • 13
  • 30