6

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 Answer 1

4

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

If you are like me and stumble across this post, updated phpunit has $this->expectException(\Exception::class); $this->expectExceptionCode('the_expected_code'); $this->expectExceptionMessage('Wrong exception'); Ref : stackoverflow.com/questions/61296581/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.