thatsus/test-api-protect

通过强制在测试中将第三方API客户端类进行模拟,避免调用第三方API

v1.0.1 2018-09-17 19:06 UTC

This package is not auto-updated.

Last update: 2024-09-15 04:57:48 UTC


README

通过强制在Laravel和Lumen测试中对客户端类进行模拟,避免调用第三方API。

保护Laravel测试中的任何类

安装

composer require thatsus/test-api-protect

添加到TestCase

  • 使用ProtectClasses trait,
  • 列出$protected_classes,并在
  • setUp中调用protectClasses。
use ThatsUs\ProtectClasses;

class TestCase extends \Illuminate\Foundation\Testing\TestCase
{
    
    use ProtectClasses;

    protected $protected_classes = [
        \Facebook\Facebook::class,
        \GuzzleHttp\Client::class,
        \App\SomeExpensiveClass::class,
    ];

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

        $this->protectClasses();
    }

    ...
}

放心犯错

想象一下,你忘记了这个无辜的类使用了 \App\SomeExpensiveClass。

class InnocentTest extends TestCase
{

    public function testInnocentMethod()
    {
        $good_guy = new Innocent();
        $this->assertTrue($good_guy->everythingIsFine());
    }
}
class Innocent 
{

    public function everythingIsFine()
    {
        app('App\SomeExpensiveClass')->doThing();
        return true;
    }
}

现在你遇到了这个错误。

PHPUnit 5.7.16 by Sebastian Bergmann and contributors.

..E..                                                               5 / 5 (100%)

Time: 152 ms, Memory: 14.00MB

There was 1 error:

1) ThatsUs\InnocentTest::testInnocentMethod
Exception: The App\SomeExpensiveClass instance is protected for tests. Setup 
a mock object using App::bind('App\SomeExpensiveClass', Closure). Method 
called: doThing.

./vendor/ThatsUs/FakeProtectedClass.php:21
./src/Innocent.php:10
./tests/InnocentTest.php:15

ERRORS!
Tests: 5, Assertions: 6, Errors: 1.

你刚刚救了自己免受危险!给自己鼓掌,然后去编辑那个测试文件。

use Illuminate\Support\Facades\App;
use Mockery;

class InnocentTest extends TestCase
{

    public function testInnocentMethod()
    {
        App::bind(\App\SomeExpensiveClass::class, function () {
            $mock = Mockery::mock(\App\SomeExpensiveClass::class);
            $mock->shouldReceive('doThing')->once();
            return $mock;
        });

        $good_guy = new Innocent();
        $this->assertTrue($good_guy->everythingIsFine());
    }
}

无麻烦

如果被测试的代码仅实例化一个类,而不调用它的任何方法,则不会抛出异常。

贡献

如果你发现了一个bug或者想为代码或文档做出贡献,你可以通过提交一个问题或一个pull request来帮忙。

许可

MIT