Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phpunit testing expectedException not working

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.

like image 347
Tornike Avatar asked Apr 29 '15 10:04

Tornike


1 Answers

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();
}
like image 144
ThW Avatar answered Oct 29 '22 02:10

ThW