Laravel/PHPUnit:Class 测试 运行 时不被模拟

Laravel/PHPUnit: Class not being mocked when tests are run

我正在测试一个调用自定义服务的 class 并想模拟该自定义服务。

错误是:

App\Jobs\CustomApiTest::getrandomInfo
Error: Call to a member function toArray() on null

这是因为在 getrandomInfo() 中有一个获取 ID 的数据库调用,测试数据库当前返回 null 因为没有条目,但测试不应该走那么远,因为我在嘲笑getData 函数。

机器配置:

Laravel 5.2

PHPUnit 4.8

我无法更新我的配置。

MainClass.php

namespace App\Jobs;
use App\Services\CustomApi;

class MainClass
{
    public function handle()
    {
        try {
            $date = Carbon::yesterday();
            $data = (new CustomApi($date))->getData();
        } catch (Exception $e) {
            Log::error("Error, {$e->getMessage()}");
        }
    }
}

MainClassTest.php

nameSpace App\Jobs;
use App\Services\CustomApi;
class MainClassTest extends \TestCase
{
    /** @test */
    public function handleGetsData()
    {
    $data = json_encode([
            'randomInfo' => '',
            'moreInfo' => ''
        ]);
    $customApiMock = $this->getMockBuilder(App\Services\CustomApi::class)
            ->disableOriginalConstructor()
            ->setMethods(['getData'])
            ->getMock('CustomApi', ['getData']);
        $customApiMock->expects($this->once())
            ->method('getData')
            ->will($this->returnValue($data));

        $this->app->instance(App\Services\CustomApi::class, $customApiMock);

    (new MainClass())->handle();
    }
}

CustomApi 代码段

namespace App\Services;
class CustomApi
{
    /**
     * @var Carbon
     */
    private $date;

    public function __construct(Carbon $date)
    {
        $this->date = $date;
    }

    public function getData() : string
    {
        return json_encode([
            'randomInfo' => $this->getrandomInfo(),
            'moreInfo' => $this->getmoreInfo()
        ]);
    }
}

我已经尝试了上述代码的多种变体,包括:

Not using `disableOriginalConstructor()` when creating $externalApiMock.
Not providing parameters to `getMock()` when creating $externalApiMock.
Using `bind(App\Services\CustomApi::class, $customApiMock)` instead of instance(App\Services\CustomApi::class, $customApiMock) for the app.
Using willReturn($data)`` instead `will($this->returnValue($data))`.

我最终创建了一个服务提供商并将其注册到 app.php 文件中。应用程序似乎没有将实例保存在容器中,而是在绑定到服务时起作用。