phpunit testing expectedException not working

我的未来我决定 提交于 2019-12-12 11:03:48

问题


I am trying to test my class for InvalidArgumentException but I get

Tests\BarTest::should_receive_parameter Missing argument 1 for Itdc\Foo\Bar::__construct(), called in /mypath/foo/tests/BarTest.php on line 10 and defined

This is the test (BarTest.php) file I use:

<?php namespace Tests;
use Itdc\Foo\Bar;
class BarTest extends \PHPUnit_Framework_TestCase {
    /** @test */
    public function should_receive_parameter() {
        $this->setExpectedException('Exception');
        $id = new Bar;
    }
}

This is Bar class:

<?php namespace Itdc\Foo;
class Bar {
    public function __construct($a) {
        // do something
    }
}

I have tried to puth setExpectedException in comment section, also tried to use InvalidArgumentException, but no luck.

Any suggetions what I am doing wrong would be appreciated.


回答1:


If you catch it directly you can var_dump() the exception.

/** @test */
public function shouldThrowException() {
  try {
    new Foo();
  } catch (\Exception $e) {
    var_dump($e);
  }
}

Output:

class PHPUnit_Framework_Error_Warning#19 (9) {
  ...

So here the source does not trigger an exception but an error, PHPUnit converts the error into a specific exception. But it does not include it in the assertions.

Try using the specific exception name:

/** @test */
public function shouldThrowException() {
  $this->setExpectedException('PHPUnit_Framework_Error_Warning');
  new Foo();
}


来源:https://stackoverflow.com/questions/29940377/phpunit-testing-expectedexception-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!