如何使用PHPUnit对无效参数进行单元测试?

4

我正在学习单元测试。这段 PHP 代码

class Foo {
    public function bar($arg) {
        throw new InvalidArgumentException();
    }
}

...

class FooTest extends PHPUnit_Framework_TestCase {
    public function testBar() {
        $this->setExpectedException('InvalidArgumentException');
        $dummy = Foo::bar();
    }
}

使用phpunit时,执行Failed asserting that exception of type "PHPUnit_Framework_Error_Warning" matches expected exception "InvalidArgumentException"导致失败。如果在Foo::bar()测试中放置任何值,则它会按预期工作。有没有一种方法可以测试空参数?或者我是错误地尝试创建一个不应该在单元测试范围内的测试?


1
bar() 应该声明为 static,因为您在没有 $this 的情况下调用它。 - yegor256
2个回答

6

你不应该测试这样的情况。单元测试的目的是确保被测试的类按照其“合同”(即其公共接口(函数和属性))执行。你试图做的是打破这个合同。正如你所说的,这超出了单元测试的范围。


如果被测试的类不是一个契约/接口的实现,那该怎么办? - BlackPanther

2

在测试合同方面,我同意 'yegor256' 的看法。然而,有时我们会有争论,是否应该使用先前声明的值,但如果它们没有设置,则抛出异常。下面是稍微修改过的代码版本(简单示例,不适合生产),附带测试代码。

class Foo {
    ...
    public function bar($arg = NULL)
    {
        if(is_null($arg)        // Use internal setting, or ...
        {
                  if( ! $this->GetDefault($arg)) // Use Internal argument
                  {
                       throw new InvalidArgumentException();
                  }
        }
        else
        {
            return $arg;
        }
    }
}

...
class FooTest extends PHPUnit_Framework_TestCase {
    /**
     * @expectedException InvalidArgumentException
     */
    public function testBar() {
        $dummy = Foo::bar();
    }

    public function testBarWithArg() {
        $this->assertEquals(1, Foo:bar(1));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接