1

when I run test with mockery on laravel, this error message:

Mockery\Exception\InvalidCountException: Method findOrFail(1) from Mockery_0__Customer should be called exactly 1 times but called 0 times

TestCase

public function createApplication()
{
    $app = require __DIR__.'/../bootstrap/app.php';

    $app->make(Kernel::class)->bootstrap();

    return $app;
}

protected function seeJsonValidFailedResponse()
{
    print_r($this->response->getContent());
    $this->assertEquals(400, $this->response->status());
    return $this;
}

protected function seeJsonValidResponse()
{
    print_r($this->response->getContent());
    $this->assertEquals(200, $this->response->status());
    return $this;
}

public function setUp()
{
    parent::setUp();
}

public function tearDown()
{
    parent::tearDown();
}

CustomerTest

use Mockery;

class CustomerTest extends TestCase
{

    use WithoutMiddleware;

    public function testIndexSuccess()
    {
        $idCustomer= 1;

        $mockCustomer = Mockery::mock('Customer');
        $mockCustomer
            ->shouldReceive('findOrFail')
            ->once()
            ->with($idCustomer)
            ->andReturn(true);

        $this->app->instance('Customer', $mockCustomer);
        $this->get('/customer/history/' . $idCustomer)
             ->seeJsonValidResponse();
    }
}

Controller

use App\Customer;

class CustomerController extends Controller
{

    public function __construct(Customer $customer) {
        $this->customerModel =  $customer;
    }

    public function history($id)
    {
        $customer = $this->customerModel->findOrFail($id);
        $issues = $customer->issues();
        return view('customer/history', compact('customer', 'issues'));
    }
}
kenorb
  • 155,785
  • 88
  • 678
  • 743
daniel lopez
  • 23
  • 1
  • 5
  • Related: [Mock should be called exactly 1 times but called 0 times](https://stackoverflow.com/q/33070381/55075) – kenorb Feb 22 '18 at 13:20

1 Answers1

1

You should add the whole namespace for the Customer class when defining the mock. So change this line:

$mockCustomer = Mockery::mock('Customer');

to this:

$mockCustomer = Mockery::mock('App\Customer');
Fredrik Schöld
  • 1,588
  • 13
  • 20