模拟对象给出错误的方法调用异常PHPUnit

时间:2018-02-12 15:40:30

标签: php unit-testing laravel-5

测试以下方法

public function handle($loginDetails): User
{
    $authUser = $this->user->where('user_id', $loginDetails->id)->first();
    if (!$authUser) {
        $authUser = $this->user->create([
            'name' => $loginDetails->name,
            'email' => $loginDetails->email,
            'profile_image' => $loginDetails->avatar_original,
            'user_id' => $loginDetails->id
        ]);
    }

    return $authUser;
}

我正在嘲笑并测试它,如下所示

public function shouldHandleNewUser()
{
        $mockBuilder = $this->getMockBuilder(Builder::class)
            ->disableOriginalConstructor()
            ->setMethods(['first'])
            ->getMock();
        $mockBuilder->method('first')
            ->willReturn(null);

        $mockUser = $this->getMockBuilder(User::class)
            ->disableOriginalConstructor()
            ->setMethods(['where', 'create'])
            ->getMock();

        $mockUser->method('where')
            ->willReturn($mockBuilder);

        $mockUser->method('create')
            ->willReturn(new User());

        $loginDetails = new class {
            public $id = 1;
            public $name = 'testUser';
            public $email = 'test@test.com';
            public $avatar_original = 'http://someurl.com/image.jpg';
        };

        $registrationHandler = new RegistrationHandler($mockUser);
        $this->assertInstanceOf(User::class, $registrationHandler->handle($loginDetails));
}

当它到达create方法时它正在抛出

PHPUnit_Framework_MockObject_BadMethodCallException

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您无法使用PHPUnit模拟static方法(我假设User::create()是静态的)。

  

限制:最终,私有和静态方法

     

请注意,finalprivateprotected static 方法不能   被诅咒或嘲笑。它们被PHPUnit的test double忽略   功能并保留其原始行为。

曾经有一种staticExpects()方法来解决它。它在PHPUnit 3.8中已弃用,并在PHPUnit 3.9中删除。作为Sebastian Bergmann says,解决方案是不使用static方法(我同意他的意见)