How to check the exception thrown correctly by PHPUnit?

Ruwantha picture Ruwantha · May 4, 2012 · Viewed 11.5k times · Source

I have div() in Cal class in my CalTest class has following methods to test the div().

public fucnction div($a,$b){
   if($b == 0){
    throw new Exception("Divided by zero");
   }
   return $a/$b
}

I can pass only testDiv() but testDiv2().

enter image description here

I want to catch check wheather the exeption thrown correctly using PHPUnit. What am I missing here?? Your help is highly appreciated. Thank you!

enter image description here

Answer

cweiske picture cweiske · May 4, 2012

Your 2nd screenshot (the one with the error) has

"@expectedException Exception"

while the third has

@expectedException InvalidArgumentException

Do you really still get the error? Did you save the file?


Works for me:

Foo.php

<?php

class Foo
{
    static function t()
    {
        throw new InvalidArgumentException('Hi there');
    }
}

?>

FooTest.php

<?php
require_once 'Foo.php';
class FooTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testT()
    {
        Foo::t();
    }
}

?>

Result

$ phpunit .
PHPUnit 3.6.10 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 5.25Mb

OK (1 test, 1 assertion)