gpt4 book ai didi

php - PHPUnit 中的模拟 - 具有不同参数的同一方法的多个配置

转载 作者:IT王子 更新时间:2023-10-28 23:56:40 26 4
gpt4 key购买 nike

可以这样配置PHPUnit mock吗?

$context = $this->getMockBuilder('Context')
->getMock();

$context->expects($this->any())
->method('offsetGet')
->with('Matcher')
->will($this->returnValue(new Matcher()));

$context->expects($this->any())
->method('offsetGet')
->with('Logger')
->will($this->returnValue(new Logger()));

我使用 PHPUnit 3.5.10,当我请求 Matcher 时它失败了,因为它需要“Logger”参数。就像第二个期望是重写第一个,但是当我转储模拟时,一切看起来都很好。

最佳答案

遗憾的是,默认的 PHPUnit Mock API 无法做到这一点。

我可以看到两个选项可以让您接近这样的事情:

使用 ->at($x)

$context = $this->getMockBuilder('Context')
->getMock();

$context->expects($this->at(0))
->method('offsetGet')
->with('Matcher')
->will($this->returnValue(new Matcher()));

$context->expects($this->at(1))
->method('offsetGet')
->with('Logger')
->will($this->returnValue(new Logger()));

这会工作得很好,但你测试的比你应该测试的要多(主要是它首先被匹配器调用,这是一个实现细节)。

如果您多次调用每个函数,这也会失败!


接受两个参数并使用 returnCallBack

这是更多的工作,但效果更好,因为您不依赖于调用的顺序:

工作示例:

<?php

class FooTest extends PHPUnit_Framework_TestCase {


public function testX() {

$context = $this->getMockBuilder('Context')
->getMock();

$context->expects($this->exactly(2))
->method('offsetGet')
->with($this->logicalOr(
$this->equalTo('Matcher'),
$this->equalTo('Logger')
))
->will($this->returnCallback(
function($param) {
var_dump(func_get_args());
// The first arg will be Matcher or Logger
// so something like "return new $param" should work here
}
));

$context->offsetGet("Matcher");
$context->offsetGet("Logger");


}

}

class Context {

public function offsetGet() { echo "org"; }
}

这将输出:

/*
$ phpunit footest.php
PHPUnit 3.5.11 by Sebastian Bergmann.

array(1) {
[0]=>
string(7) "Matcher"
}
array(1) {
[0]=>
string(6) "Logger"
}
.
Time: 0 seconds, Memory: 3.00Mb

OK (1 test, 1 assertion)

我在匹配器中使用了 $this->exactly(2) 来表明这也适用于对调用进行计数。如果您不需要,将它换成 $this->any() 当然可以。

关于php - PHPUnit 中的模拟 - 具有不同参数的同一方法的多个配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5484602/

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