squibby's avatar

Testing controller & mocking request

Hi, Struggling to get to grips with some basic testing. I have a store method on user controller which receives form data and uses a form request class for validation.

I want to test this using php unit but have no idea how I can pass some dummy data to the user controller and check that everything works, and also check the validation is working as expected. Do i need to mock the class in some way? I have dug around and seen something called Mockery? But also seen that things can be mocked within phpunit itself using $this->getMock

This is wahts happening in the controller:

public function store(createUserRequest $request){

        if($request->persist()){
            flash('User added successfully', 'success');
        } else {
            flash('User not added', 'warning');
        }
        
        return Redirect('/users');
            
    }

This is the form request class

namespace App\Http\Requests;

use App\Http\Requests\Request;
use App\User;

class createUserRequest extends Request
{


    public function authorize(){
        return true;
    }


    public function rules(){
        return [
            'name'                              => 'required|max:50',
            'surname'                           => 'required|max:50',
            'password'                          => 'required|min:6',
            'email'                             => 'required|email|unique:users|max:250',
            'work_mobile_code'                  => 'required',
            'work_mobile'                       => 'required',
            'notes'                             => 'max:500'
        ];
    }

    public function persist(){

        $user            = new User($this->all());
        $user->password  = bcrypt($this->password);
        $user->api_token = str_random(60);

        if($user->save()){
            return true;
        }

        return false;

    }




}

Do I need to split things up and test the controller method by itself, and then test the for request class seperatly in another test? And if so what is the way to that?

Thanks

0 likes
2 replies
ifpingram's avatar
Level 4

@squibby Testing controllers is easiest using the Laravel integrated package, as opposed to PHPUnit itself. You have nothing really to mock out here, so you're investigating a solution to a different problem.

This said, I would not really bother testing the above as there is not a lot of bespoke non-framework logic in your code. I would certainly TDD to arrive at the above code, but now it is written, there isn't much you can actually test beyond a simple catch-all regression test to ensure that the request rules are doing what they should.

1 like

Please or to participate in this conversation.