2

I'm new to unit testing and have written the following test:

/**
 * @expectedException Exception
 */
public function testCantGetInvalidCampsite() {
    $invalidIds = array(300000, "string");
    foreach($invalidIds as $id) {
        $this->campsites->getCampsite($id); // will throw an exception
    }
}

I'm not sure though if this is actually testing all the invalid ids, or just stopping as soon as it hits the first exception. Is this how I should be testing for multiple exceptions or do I need to split this up into a number of different tests, or is there another way I should do it?

Also, if my exception message is generated dynamically eg "Could not retrieve record with id 30000", how do I test that the correct dynamic message is being produced?

2 Answers 2

10

The approach I use in this situation is using phpunit dataProviders:

class MyTest extends PHPUnit_Framework_TestCase
{
    public function invalidIds()
    {
       return array(
           array(300000),
           array("string")
       );
    }


    /**
     * @dataProvider invalidIds
     * @expectedException Exception
     */
    public function testCantGetInvalidCampsite($invalidId)
    {
        $this->campsites->getCampsite($invalidId); // will throw an exception
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could try to catch the Exceptions, count them and fail the Test if the number of expected Exceptions does not match the number of encountered Exceptions. Of

You could also fetch the Message of the Exception, if you encounter one, and check if it is correct.

In Code:

public function testCantGetInvalidCampsite() {
    $invalidIds = array(300000, "string");
    $exceptionCount = 0;

    foreach($invalidIds as $id) {

        try {
            $this->campsites->getCampsite($id); // will throw an exception
        } catch (Exception $e)
            $exceptionCount ++;
            $this->assertEquals('my exception message', $e->getMessage());
        }
    }

    // assert here that exception count is two
    $this->assertEquals(2, $exceptionCount);
}

The cleaner Way, in my opinion to do it would be to add two TestCases ...

testCantGetInvalidCampSite_String()
testCantGetInvalidCampSite_InvalidId()

so you see instantly what fails if the test fails.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.