我有一个方法,它将在一个测试中被多次调用,但每次参数只调用一次。所以我想测试一下这个方法只接收到每个参数一次。例如,这里有一个mkdir函数,它与每个目录一起调用以创建:
测试
$dirs = [
"$parentDir/$siteName/assets/components",
"$parentDir/$siteName/assets/layouts",
];
// iterate each directory
foreach($dirs as $dir) {
// and verify that mkdir was called with that argument only once
$fileSystemMock->expects($this->once())
->method('mkdir')
->with($this->equalTo($dir));
}正在测试的方法
public function createSite($siteName) {
$fileSystem = $this->fileSystem;
$parentDir = $this->parentDir;
$componentsDir = "$parentDir/$siteName/assets/components";
$layoutsDir = "$parentDir/$siteName/assets/layouts";
$mediaDir = "$parentDir/$siteName/content/media";
$sectionsDir = "$parentDir/$siteName/assets/sections";
if (!$fileSystem->exists($componentsDir)) {
$fileSystem->mkdir($componentsDir);
}
if (!$fileSystem->exists($layoutsDir)) {
$fileSystem->mkdir($layoutsDir);
}然而,测试失败了:
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'/path/to/parent/best-widgets/assets/layouts'
+'/path/to/parent/best-widgets/assets/components'希望我想要的是有意义的。once()不考虑with()参数吗?我不知道如何检查每个参数都调用了一次方法
发布于 2020-01-27 23:41:19
您可以使用withConsecutive
$fileSystemMock->expects($this->exactly(count($dirs)))
->method('mkdir')
->withConsecutive(...array_map(function (string $dir) {
return [$this->equalTo($dir)];
}, $dirs));withConsecutive为每组参数期望都期望一个参数,因此array_map与解包装运算符相结合会派上用场。
请注意,只有在调用按$dirs数组定义的相同顺序进行时,才会发生这种情况。否则它似乎更难实现(顺便说一句,最近创建了一个GitHub问题 )。
以上版本的PHP7.4奖金:
$fileSystemMock->expects($this->exactly(count($dirs)))
->method('mkdir')
->withConsecutive(...array_map(fn(string $dir) => [$this->equalTo($dir)], $dirs));https://stackoverflow.com/questions/59940048
复制相似问题