iamamirsalehi's avatar

How to write some test for a controller that is using repository pattern

Hey there. How can I write some test for a controller that is using repository pattern?

0 likes
6 replies
martinbean's avatar
Level 80

@isamirsalehi What’s a “repository pattern” got to do with how you test a controller? Just test it like you would any other scenario:

public function testExample(): void
{
    $this->get('/uri')->assertOk();
}

If your repository is resolved by the container, you can mock it and set some expectations:

public function testListingOrders(): void
{
    $this->mock(OrderRepository::class, function ($mock) {
        $mock->shouldReceive('all')->once()->andReturn(new Collection());
    });

    $this->get('/orders')->assertOk();
}

But this is just testing how your code’s put together, and not if your code actually works in my opinion. If you re-factor your controller, your test is going to break, because it’s asserting how you’ve coded your controller and not how your controller is actually working.

For example, if you remove the repository and just use an Eloquent model and return the same data as the repository, the controller would still be working, but your test would break.

1 like
iamamirsalehi's avatar

@martinbean thank you so much, this my code in the controller

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repository\Contracts\Trade\TradeRepositoryInterface;

class USDTController extends Controller
{
    public $tradeRepository;

    public function __construct()
    {
        $this->tradeRepository = resolve(TradeRepositoryInterface::class);
    }

    public function all()
    {
        $usdt =  $this->tradeRepository->getUSDTPricesAsJson();

        return response()->json($usdt);
    }
}

I wanna write some test for it

martinbean's avatar

@isamirsalehi Why are you using the resolve helper? The entire point of dependencies in a constructor is to be able to type-hint them and have them resolved by the container:

protected $tradeRepository;

public function __construct(TradeRepositoryInterface $tradeRepository)
{
    $this->tradeRepository = $tradeRepository;
}

Please or to participate in this conversation.