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

Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't this just test the exception? Will the save function continue to test?
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

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.