我有一个PHP单元,如下所示:
class Challenge1Test extends TestCase
{
/**
* @dataProvider invalidConstructorValues
*/
public function test_throws_exception_for_initial_value(int $value): void
{
$this->expectException(\OutOfRangeException::class);
new ImmutableWeekDay($value);
}
//...
}它正在测试我类的__construct(),如果值超出了范围,则返回OutOfRangeException。我正在用数据进行测试,这些数据预计会抛出错误。
/**
* @throws \OutOfRangeException
*/
public function __construct(int $value)
{
$this->value = $value;
}上述结果给出了错误数据输入的预期错误。
我试图通过测试,所以我只在满足范围要求时初始化该var。
/**
* @throws \OutOfRangeException
*/
public function __construct(int $value)
{
$refl = new \ReflectionClass($this);
$this->value = null;
foreach($refl->getConstants() as $k=> $v){
if ($v = $value){
$this->value = $value;
}
}
}但我还是得到了坏数据的例外情况。在我的控制器中是否有一种不修改测试以通过测试的方法?
链接到我在这里的php沙箱代码:https://phpsandbox.io/n/old-term-kkap-0hqmq?files=%2Fsrc%2FChallenge1%2FImmutableWeekDay.php
发布于 2022-06-24 19:52:08
在这个测试中,test_throws_exception_for_initial_value至少缺少使用异常的条件,但是我会检查函数调用的$value是否是正确的对象。我认为这是正确的。
public function test_throws_exception_for_initial_value(int $value): void
{
$act = (Object) new ImmutableWeekDay($value);
$this->assertIsObject($act);
}但是,在构造函数中,我将检查在调用中传递的$value是否在正确的范围内。
public function __construct(int $value)
{
$this->value = null;
$wynik = -1;
$a = new \ReflectionClass($this);
foreach ($a->getConstants() as $v){
$wynik = $v;
}
if ($value >= 0 && $value <= $wynik)
$this->value = $value;
}https://stackoverflow.com/questions/70949624
复制相似问题