【问题标题】:Laravel mocking is not executingLaravel 模拟未执行
【发布时间】:2020-06-10 13:09:31
【问题描述】:

我一直在尝试在 Laravel 6 单元测试中模拟服务类,但调用正在转移到真实方法而不是模拟响应。这是我要模拟的 People 类 -

class People
{ 
    public static function checkCredentials($username, $password) {
        // some code, which is not supposed to execute while unit testing. 
    }
}

负责执行此操作的控制器是 -

class AuthController extends Controller {
    public function login(Request $request) {
        $auth = People::checkCredentials($request->username, $request->password);
        dd($auth);  // I am expecting mocked response here i.e., ['abc'].
    }
}

这是我的测试课-

class LoginTest extends TestCase {
    /** @test */
    public function a_user_can_login() {
         $this->mock(People::class, function ($mock) {
            $mock->shouldReceive('checkCredentials')
                    ->withArgs(['username', 'password'])
                    ->once()
                    ->andReturn(['abc']);
        });
        $this->assertTrue(true);
    }
}

控制器中的转储返回的是真实的响应,而不是模拟的。我需要帮助来了解我做错了什么。谢谢。

【问题讨论】:

    标签: laravel unit-testing mocking laravel-6 mockery


    【解决方案1】:

    为了模拟服务,必须将服务作为服务容器注入。

    目前您正在调用 People 类的静态方法,而没有实例化该类。

    $auth = People::checkCredentials($request->username, $request->password);

    尝试将类作为服务容器注入,以便 Laravel 可以捕获并模拟它。您可以将其键入提示作为函数的参数。

    class AuthController extends Controller {
        public function login(Request $request, $people People) {
            $auth = $people::checkCredentials($request->username, $request->password);
            dd($auth);  // I am expecting mocked response here i.e., ['abc'].
        }
    }
    

    Mocking objects

    Service Container

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2021-06-30
      • 1970-01-01
      • 2012-04-20
      • 2014-12-12
      • 2020-04-15
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多