C
C
coderisimo2017-03-13 02:18:02
Test Driven Development
coderisimo, 2017-03-13 02:18:02

How to write tests for a controller method in LARAVEL?

There is a method in the controller:

public function sendVeryficationEmail(Request $request) {
     return  $request->input('name');
    }

how to write a test for this method?
This is how it doesn't work:
$response = $this->call('post', '/user/registerrequest',['name'=>'VasyaPupkin']);

because, as I understand it, in order to call the method under test, as a controller method, you need to somehow pass the request object to it, which it expects. Moreover, in this object there can be a bunch of variables, not just one, as in the simplified example above. It is not clear how to "lock" this request object.
Of course, you can declare this method without request , it can take just a string (or an array), and you can call it through another method that you can not test for simplicity. Then testing can be done without the participation of the controller, which seems to be good, but: From one method, TWO are obtained, and the reason for the appearance of the second method is precisely in the convenience of testing, the application itself will simply become even more confusing.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xAockd, 2017-03-16
@coderisimo

You can simply create a controller instance and call the method with a parameter.

$controller = new My\Controller();
$request = Request::create('/', 'GET', ['name' => 'test']);
$this->assertEquals('test', $controller->sendVeryficationEmail($request));

How to get wet:
$request = \Mockery::mock(Request::class);
$request->shouldReceive('input')->once()->andReturn('VasyaPupkin');
$continer->instance(Request::class, $request);
$response = $this->call('post', '/user/registerrequest');
$this->assertEquals('VasyaPupkin', $response);

Where $container is a laravel container :)
And the request can either be mocked or created.
Request::create() or a mock, whichever you prefer.
But, if you want to stay on your method, you can replace the Request in the container with the same mock.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question