Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phpunit Test cases for InvalidArgumentException

Please tell how to create test cases fro below function to test exception and messages is thrown correctly. I'm using Symfony 2.

public function validateParams(Graph $graph, $start, $destination)
{
    if (!is_object($graph)) {

        throw new \InvalidArgumentException('Graph param should be an object !');
    }

    if (empty($start)) {

        throw new \InvalidArgumentException('Start param is empty !');
    }

    if (empty($destination)) {

        throw new \InvalidArgumentException('Graph param is empty !');
    }

    return true;
}

I used below test case and it says, Failed asserting that exception of type "\InvalidArgumentException" is thrown.

 /**
 * @expectedException \InvalidArgumentException
 */
public function testValidateParamsWhenStartingPointIsEmpty()
{
   $this->shortestPathCalc= new ShortestPathCalculator();
   $this->shortestPathCalc->validateParams($this->graph, ' ', 'f', 'Expected exception not thrown when starting point is empty !');
}
like image 684
Shaolin Avatar asked Apr 01 '26 12:04

Shaolin


1 Answers

The problem in your class is that the check with empty do:

From the doc

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

This test work fine for your validator class (green bar):

class ValidatorTest extends \PHPUnit_Framework_TestCase{

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage Start param is empty !
     */
    public function testA()
    {
        $validator = new Validator();
        $validator->validateParams(new Graph(),'',' ');
    }

Hope this help

like image 125
Matteo Avatar answered Apr 03 '26 12:04

Matteo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!