php - testing exceptions with phpunit -
i trying test function when know error going thrown. function looks this:
function testsetadsdata_dataisnull(){ $dataarr = null; $fixture = new adgroup(); try{ $fixture->setadsdata($dataarr); } catch (exception $e){ $this->assertequals($e->getcode(), 2); } $this->assertempty($fixture->ads); $this->assertempty($fixture->adids); }
now trying use phpunit exceptions assertions methods replace try catch part can't figure out how that. did lots of reading including post phpunit assert exception thrown? couldnt understand how shuold implemented.
i tried this:
/** * @expectedexception dataisnull */ function testsetadsdata_dataisnull(){ $dataarr = null; $fixture = new adgroup(); $this->setexpectedexception('dataisnull'); $fixture->setadsdata($dataarr); $this->assertempty($fixture->ads); $this->assertempty($fixture->adids); } didn't work , got error: 1) adgrouptest::testsetadsdata_dataisnull reflectionexception: class dataisnull not exist
what doing wrong , how can assert if exception thrown plz?
i use @expectedexception
annotations such cases. see all exception-related annotations here:
/** * @expectedexception \exception * @expectedexceptioncode 2 */ function testsetadsdata_dataisnull() { $dataarr = null; $fixture = new adgroup(); $fixture->setadsdata($dataarr); }
checking $fixture->ads
null doesn't add here, can add these asserts prior call triggers exception:
$this->assertnull($fixture->ads); $fixture->setadsdata($dataarr);//throws exception
you're unit testing. test serves clear purpose: makes sure exception thrown in given situation. if does, that's test ends.
still, if want keep assertempty
calls, this:
try { $fixture->setadsdata($dataarr); $e = null; } cathc (exception $e) {} $this->assertempty($fixture->ads); $this->assertempty($fixture->adids); if (!$e instanceof \exception) { //if exception not thát important: $this->marktestincomplete('no exception thrown'); //do other stuff here... possibly $this->fail('the exception not thrown'); } throw $e;//throw exception bit later
an alternative approach call $this->setexpectedexception
manually as explained here. since don't seem know/care exception message like, i'm going use setexpectedexceptionregexp
method:
$fixture = new adgroup(); $this->setexpectedexceptionregexp( //exception class, message regex, exception code 'exception', '/.*/'. 2 ); $fixture->setadsdata(null);//passing null seems you're doing anyway
Comments
Post a Comment