1

At the beginning of the function I am trying to test, there is a check to see that the required inputs are set. If they are not an exception is thrown:

    public function save(array $input) {
        if (!isset($input['var1']) || !isset($input['var2'])) {
            throw new BadRequestException('Invalid parameters for ' . $this->class . ':save');
        } .........rest of function

Do I need to separate this out into another function to test the exception? I know I want to test this if var1 is set and var2 is not set, as well as if var2 is set and var1 is not set. Do I test in the testSave function, or should I separate it out into another testing function? If I do test in the same function, how do I do this?

1 Answer 1

2

You can assert that a specific exception is thrown using the @expectedException annotation.

Example:

/**
 * @test
 * @dataProvider dataInvalidInput
 * @expectedException BadRequestException
 */
public function saveShouldThrowException($invalidInput)
{
    $this->subject->save($invalidInput);
}
public static function dataInvalidInput()
{
    return array(
        'var1_missing' => array('var2' => 1),
        'var2_missing' => array('var1' => 1),
        'both_missing' => array('var3' => 1),
    );
}

You can also assert code and message of the exception with @expectedExceptionCode and @expectedExceptionMessage.

Read more in the manual: Testing Exceptions

2
  • Doesn't this just test the exception? Will the save function continue to test?
    – ajw4sk
    Commented Oct 6, 2015 at 13:21
  • Ah ok, I think I get what you're saying. Test the save function with correct inputs, and then test that the exception will be thrown this way. Thank you
    – ajw4sk
    Commented Oct 6, 2015 at 13:23

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