测试以下方法
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
我在这里做错了什么?
答案 0 :(得分:1)
您无法使用PHPUnit模拟static
方法(我假设User::create()
是静态的)。
限制:最终,私有和静态方法
请注意,
final
,private
,protected
和static
方法不能 被诅咒或嘲笑。它们被PHPUnit的test double忽略 功能并保留其原始行为。
曾经有一种staticExpects()
方法来解决它。它在PHPUnit 3.8中已弃用,并在PHPUnit 3.9中删除。作为Sebastian Bergmann says,解决方案是不使用static
方法(我同意他的意见)