1

I am testing this function using PHPUnit:

public 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);
}

I was told this is not the right way and that I should use @expectedException, so I started reading the manual and some answers here including this popular one: PHPUnit assert that an exception was thrown?

But after quite a lot of reading I still didn't understand what's the benefit of using this other than my initial approach. I guess it has something to do with the fact I didn't really understand how to use it. I tried different ways, but none of them actually worked.

I realise I can add a line like this in the code :

throw new MyException('Some Error Msg', 2);

but then I need to use try catch as well (or so I understood) so what is the benefit?

Community
  • 1
  • 1
Donoven Rally
  • 1,670
  • 2
  • 17
  • 34

1 Answers1

0

There are 2 issues that I see with your test.

1) The test can pass without an exception being thrown. After your function call, you should add a $this->fail('No Exception was thrown'). Using setExpectedException will do this for you, the test will fail if you don't throw the exception. In your case, you have no failing case if this were to happen. You need to set a flag and assert that the exception was thrown after the catch block.

2) You are catching a generic exception in your test. This is not a good practice to get into. If you have a test that uses mocks, failed assertions from the mocks are signaled via an exception being thrown. Which your test here will catch and handle. Again making your test appear to pass when it actually doesn't. (This can also manifest with other assertions failing and causing much consternation when trying to fix the test).

In your example test, you want to use the try-catch because you are doing further assertions after you execute the code. setExpectedException does not allow you to do this. Behind the scenes, this method/annotation wraps your test in its own try catch and verifies the exception for you. Which many times is exactly what you are looking for.

Schleis
  • 41,516
  • 7
  • 68
  • 87