Reputation: 105
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?
Upvotes: 1
Views: 71
Reputation: 24551
You can assert that a specific exception is thrown using the @expectedException
annotation.
/**
* @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
Upvotes: 2