在流明测试中覆盖注入的类

时间:2018-06-07 11:39:46

标签: php laravel lumen mockery

我使用流明实现rest api,其中我主要使用MySql程序我有一些Connection类,Repository注入到Controllers中,但我想在Constructor中替换Connection类来测试这些存储库,因为我使用的程序我不是想要调用任何测试数据库。

示例RepositoryClass:

class UserRepository {
    protected $readConnection;

    public function __construct(MydbConnection $readConnection) {
        $this->readConnection = $readConnection;
    }

    public function checkUserPermission(username, password) {
        return $this->readConnection->callProcedure('check_perm', [username, password]);
    }

}

在测试中我有:

class AuthTest extends TestCase
{
    protected $controller;
    protected $mockConn;

    public function setUp()
    {
        parent::setUp();
        // make mockery object
        $this->mockConn = Mockery::mock(MydbConnection::class);
        $this->app->instance(MydbConnection::class, $this->mockConn);

        // try override userRepository 
        $repo = $this->app->make(UserRepository::class);
        $this->app->bind( UserRepository::class, $repo);

        // then override controller
        $this->controller = $this->app->make(AuthController::class);
        $this->app->bind(AuthController::class, function () {
            return $this->controller;
        });
    }

    public function testLogin()
    {
       $this->post('/auth/login', [
           'username' => 'test.dev',
            'password' => 'Test123'
       ]);

        $this->mockConn->shouldReceive('callProcedure');
   }
}

但这不是这样的,你能帮助我如何用mockery对象替换MydbConnection?

0 个答案:

没有答案