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

时间:2012-09-17 17:16:44

标签: unit-testing phpunit

我只是在学习单元测试。这个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()测试中放置了任何值,那么它当然可以按预期工作。有没有办法测试空参数?或者我是否错误地尝试为不应该在单元测试范围内的事物创建测试?

2 个答案:

答案 0 :(得分:6)

你不应该测试这种情况。单元测试的目的是确保被测试的类根据其“契约”执行,这是它的公共接口(函数和属性)。你要做的就是打破合同。正如你所说,它超出了单元测试的范围。

答案 1 :(得分: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));
    }
}
相关问题