Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to unit test a controller in Laravel without testing the route too

I've read lots of documentation about testing controllers using $this->call($destination, $parameters, 'GET'); but this seems to rely on the route being set up too, and knowing the right $destination to use.

Generally this is OK, but accessing a controller from a route doesn't seem right for unit testing. I want to unit test the controller, not the route. Is there a standard way to unit test controllers, without dealing with routes?

Is simply manually instantiating the controller and calling the method enough? E.g.

$controller = new MyController;
$response = $controller->someMethod($param);
$this->assertSomething($response);

Perhaps controllers shouldn't be unit tested (and only have acceptance tests) and my request is a sign that my controllers are too heavy.

like image 900
dave1010 Avatar asked Sep 26 '13 13:09

dave1010


People also ask

Should controllers have unit tests?

If you've writing custom filters, routes, etc, you should unit test them, but not as part of your tests on a particular controller action. They should be tested in isolation.

What is the difference between unit and feature test?

Feature and Unit tests are methods of software testing that isolate a part of a system and test it. A unit test could look at something small like a single method e.g. adding a row to a database, whereas a feature test will have a broader view such as registering a user and validating their details.

What is PHPUnit Laravel?

Use Laravel Unit Testing to Avoid Project-Wrecking Mistakes. Pardeep Kumar. 7 Min Read. PHPUnit is one of the most well known and highly optimized unit testing packages of PHP. It is a top choice of many developers for rectifying different developmental loopholes of the application.


2 Answers

You can call your actions directly:

$response = $this->action('GET', 'OrdersController@show', ['id' => 1]);
like image 114
Antonio Carlos Ribeiro Avatar answered Sep 28 '22 08:09

Antonio Carlos Ribeiro


The action method has been removed from Laravel 5.4 testing api

like image 30
Sarthak Khanal Avatar answered Sep 28 '22 09:09

Sarthak Khanal