gpt4 book ai didi

PHPUnit 如何使用包含 instanceOf 的数组子集来约束模拟 stub 方法输入?

转载 作者:行者123 更新时间:2023-11-28 20:39:19 24 4
gpt4 key购买 nike

我想测试一段非常具体的代码,但找不到好的方法。我有这样的代码:

public function foo()
{
try {
//...some code
$this->service->connectUser();
} catch (\OAuth2Exception $e) {
$this->logger->error(
$e->getMessage(),
['exception' => $e]
);
}
}

我想测试异常是否被抛出并记录到 $this->logger。但是我找不到一个好的方法来做到这一点。这是我目前的做法。

public function testFoo()
{
$oauthException = new \OAuth2Exception('OAuth2Exception message');

//This is a $service Mock created with $this->getMockBuilder() in test case injected to AuthManager.
$this->service
->method('connectUser')
->will($this->throwException($oauthException));

//This is a $logger Mock created with $this->getMockBuilder() in test case injected to AuthManager.
$this->logger
->expects($this->once())
->method('error')
->with(
$this->isType('string'),
$this->logicalAnd(
$this->arrayHasKey('exception'),
$this->contains($oauthException)
)
);

//AuthManager is the class beeing tested.
$this->authManager->foo($this->token);
}

这将测试是否使用特定参数调用了error 方法,但是数组键'exception' 和异常对象可以存在于数组的不同部分。我的意思是测试将通过这样的错误方法调用:

$this->logger->error(
$e->getMessage(),
[
'exception' => 'someValue',
'someKey' => $e,
]
);

我想确保 error 方法将始终接收这样的子集 ['exception' => $e]。像这样的东西是完美的:

$this->logger
->expects($this->once())
->method('error')
->with(
$this->isType('string'),
$this->arrayHasSubset([
'exception' => $oauthException,
])
);

用PHPUnit可以实现吗?

最佳答案

您可以使用 callback() 约束:

public function testFoo()
{
$exception = new \OAuth2Exception('OAuth2Exception message');

$this->service
->expects($this->once())
->method('connectUser')
->willThrowException($exception);

$this->logger
->expects($this->once())
->method('error')
->with(
$this->identicalTo($exception->getMessage()),
$this->logicalAnd(
$this->isType('array'),
$this->callback(function (array $context) use ($exception) {
$expected = [
'exception' => $exception,
];

$this->assertArraySubset($expected, $context);

return true;
})
)
);

$this->authManager->foo($this->token);
}

参见 https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects :

The callback() constraint can be used for more complex argument verification. This constraint takes a PHP callback as its only argument. The PHP callback will receive the argument to be verified as its only argument and should return true if the argument passes verification and false otherwise.

另请注意我是如何调整设置您的测试替身的:

  • 期望方法 connectUser() 只被调用一次
  • 使用$this->willThrowException()代替$this->will($this->throwException())
  • 使用 $this->identicalTo($exception->getMessage()) 而不是更松散的 $this->isType('string')

我总是尽量使论证尽可能具体,并且只放松对意图的限制。

关于PHPUnit 如何使用包含 instanceOf 的数组子集来约束模拟 stub 方法输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com