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

Unit testing 如何使用phpunit对无效参数进行单元测试?,unit-testing,phpunit,Unit Testing,Phpunit,我只是在学习单元测试。这是php代码 class Foo { public function bar($arg) { throw new InvalidArgumentException(); } } 失败,无法断言类型为“PHPUnit\u Framework\u Error\u Warning”的异常与预期的异常“InvalidArgumentException”匹配。来自PHPUnit。如果在Foo::bar()test中放置了任何值,那么它当然会按预期

我只是在学习单元测试。这是php代码

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


失败,
无法断言类型为“PHPUnit\u Framework\u Error\u Warning”的异常与预期的异常“InvalidArgumentException”匹配。
来自PHPUnit。如果在
Foo::bar()
test中放置了任何值,那么它当然会按预期工作。有没有办法测试空参数?还是我错误地试图为不应该在单元测试范围内的东西创建测试?

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

我同意“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));
    }
}

bar()
应该声明为
static
,因为您在调用它时没有
$this
如果被测试的类不是契约/接口的实现怎么办?
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));
    }
}