1

i started using phpunit and came across this issue im wondering what is the best way to deal with it. I am testing the following function:

/**
 * @expectedException PHPUnit_Framework_Error
 */
function testSetAdsData_dataIsNull()
{
    $dataArr = null;
    $fixture = new AdGroup();
    $fixture->setAdsData($dataArr);

    $this->assertEmpty($fixture->ads);
    $this->assertEmpty($fixture->adIds);
}

now the line $fixture->setAdsData($dataArr); throws an exception as i want and that's ok, but the problem is the following two assertions won't execute. so i read about it and understood that if i want to execute the two following assertions i need to use try/catch , so my question is, what is the correct way to do that? i tried doing this:

/**
 * @expectedException PHPUnit_Framework_Error
 */
function testSetAdsData_dataIsNull()
{
    $dataArr = null;
    $fixture = new AdGroup();
    try{
    $fixture->setAdsData($dataArr);
  } catch (Exception $e){
    $this->assertEmpty($fixture->ads);
    $this->assertEmpty($fixture->adIds);
  }
}

but now the exception is not thrown. should i leave it this way and just remove the expectation part from the top or is there a better way to do that?? thx

1 Answer 1

1

Yes, you need to get rid of the expectedException annotation. You're catching the exception so it won't be thrown now. Indeed, there is another problem: now, if the Exception is not thrown, the test will pass.

The solution is use a return sentence after the assertions, and making the test fail manually when the Exception is not thrown:

function testSetAdsData_dataIsNull()
{
    $dataArr = null;
    $fixture = new AdGroup();
    try {
        $fixture->setAdsData($dataArr);
    } catch (Exception $e){
        $this->assertEmpty($fixture->ads);
        $this->assertEmpty($fixture->adIds);
        return;
    }
    $this->fail('Exception not thrown');
}

Another recommendation: use Exception subclasses. If an Exception is thrown but not for the reason you expect, the test will pass but maybe the behaviour is not the expected in the real code. If you catch only a certain type of exception, you will be sure that the Exception was raised for the right reason.

Not the answer you're looking for? Browse other questions tagged or ask your own question.