【问题标题】:InvalidCountException: Method should be called exactly 1 times but called 0 timesInvalidCountException:方法应该被准确调用 1 次但被调用 0 次
【发布时间】:2017-01-03 10:47:40
【问题描述】:

当我在 laravel 上使用 mockery 运行测试时,出现以下错误消息:

Mockery\Exception\InvalidCountException:来自 Mockery_0__Customer 的方法 findOrFail(1) 应该被准确调用 1 次,但被调用 0 次

测试用例

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();
}

客户测试

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();
    }
}

控制器

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'));
    }
}

【问题讨论】:

标签: mockery laravel-5.3


【解决方案1】:

在定义模拟时,您应该为 Customer 类添加整个命名空间。所以改变这一行:

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

到这里:

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

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 2020-09-15
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多