Laravel / PHPUnit:运行测试时不会模拟类

时间:2018-09-08 21:28:56

标签: laravel mocking phpunit lumen phpunit-testing

我正在测试一个调用自定义服务的类,并希望模拟出该自定义服务。

错误是:

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))`.

1 个答案:

答案 0 :(得分:0)

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