How to validate Laravel 5 controller methods

We have a Laravel 5 controller method:

public function getInput()
    $input = \Request::all();
    $links = $input['links'];
    $this->startLinks =  explode("\n", $links);
    return $this;


How can we test this single method? I don't understand how to pass a POST request with data to this method? And how do I instantiate this controller class in my test method?


source to share

2 answers

It looks like a method that probably shouldn't belong to the controller. If you're serious about testing, I highly recommend reading the sample repository. When testing, it will be much easier for you to get rid of all the controllers. =

With that said, this is still very easy to test. The main idea is to figure out what needs to be tested and ONLY test it. This means that we don't care what the dependencies do, just what they do and returns what the rest of the method requires. In this case, it is the facade Request


Then you want to make sure that the variables are set appropriately and that the method returns an instance of that class. It actually ends up pretty straightforward.

It should look something like this ...

public function testGetInput()
    $requestParams = [
        'links' => "\\\"

    // Here we are saying the \Request facade should expect the all method to be called and that all method should
    // return some pre-defined things which we will use in our asserts.

    // Here we are just using Laravel IoC container to instantiate your controller.  Change YourController to whatever
    // your controller is named
    $class = App::make('YourController');

    // Getting results of function so we can test that it has some properties which were supposed to have been set.
    $return = $class->getInput();

    // Again change this to the actual name of your controller.
    $this->assertInstanceOf('YourController', $return);

    // Now test all the things.
    $this->assertTrue(in_array('', $return->startLInks));
    $this->assertTrue(in_array('', $return->startLInks));
    $this->assertTrue(in_array('', $return->startLInks));
    $this->assertTrue(in_array('', $return->startLInks));




I think you are looking for this .

If your test class expands TestCase

, you will end up with many helper methods that will do the heavy lifting for you.

function testSomething() {
    // POST request to your controller@action
    $response = $this->action('POST', 'YourController@yourAction', ['links' => 'link1 \n link2']);
    // you can check if response was ok
    $this->assertTrue($response->isOk(), "Custom message if something went wrong");
    // or if view received variable
    $this->assertViewHas('links', ['link1', 'link2']);


Codeception extends this functionality even further.



All Articles