vendredi 26 mai 2017

Testing store method in Controller

I am new to testing.

I have controller in Laravel and I want to test the store method.

This is my controller.

class ClientsController extends Controller
{
    protected $client;

    public function __construct(App\Client $client)
    {
        $this->client = $client;
    }

    public function index()
    {
        $clients = $this->client->all();

        return view('clients::index')->with('clients', $clients);
    }

    public function create()
    {
        return view('clients::create');
    }

    public function store(App\Requests\CreateClientRequest $request)
    {

        $this->client->create( $request->only(['name', 'head_person','address','primary_email','contact_no']) );

        return redirect()->route('clients.show', ['id' => $this->client->id]);
    }

    public function show($id)
    {
        $client = $this->client->find($id);
        return view('clients::show')-with('client',$client);
    }
}

I have written a test but it fails. I cannot find out where i am wrong.

Here's the test

class ClientsControllerTest extends TestCase
{
    use DatabaseMigrations;

    protected $user;

    public function __construct()
    {
        $this->clientsMock = \Mockery::mock('Eloquent','App\Client');
    }

    /**
     * 
     * @before
     */
    public function runSetupBeforeClass()
    {
        parent::setup();

        $this->app->instance('App\Client',$this->clientsMock);
    }

    public function tearDown()
    {
        \Mockery::close();
    }

    /**
     * 
     @test
     */
    public function shouldAddsNewClient()
    {
        $client = factory(Client::class)->make();

        Input::replace($input = [
                            'name'  => $client->name,
                            'head_person' => $client->head_person,
                            'address'   => $client->address,
                            'primary_email'  => $client->primary_email,
                            'contact_no'   => $client->contact_no,
                        ]);

        $this->clientsMock
            ->shouldReceive('create')
            ->once();
            ->with($input);

        $response = $this->post('/clients');    

        $response->assertStatus(302)
                ->assertRedirect(route('clients.show'));
    }

Please help me with this. How should I write my tests for the store method.

Aucun commentaire:

Enregistrer un commentaire