0

I have the following code that creates a new user. I am using PHPUnit to prepare test cases but however my code coverage is unable to cover the exception case i.e. throw new Exception(__CLASS__ . ': Invalid data');.

Can someone please show me how to cover the exception case in phpunit using assertInstanceOf() or something else?

/**
* Creates a new user
*
* @param string            $email
* @param UserType       $UserType
*
* @return UserID
* @throws Exception If Invalid Data is Provided
*/
static public function Create($email, UserType $UserType)
{
    if (!$UserType instanceof UserType) {
        throw new Exception(__CLASS__ . ': Invalid data');
    }

    $UserID = parent::Create($email, $UserType);

    return $UserID;

}

Many thanks

3
  • Guys, please do not come to a conclusion of making this a duplicate post without even knowing what I am exactly looking for. The link you posted is of no help to me since it does not say anything about handling the exception of type hinting. Thanks Commented Nov 3, 2013 at 9:43
  • How is that not a duplicate? Commented Nov 3, 2013 at 12:03
  • As the asker of the question it is up to you to tell us what you are 'exactly looking for'. How else do you expect to get an answer? Commented Nov 3, 2013 at 16:00

1 Answer 1

1

Write a test where you put something else then an instance of the right class into parameter $UserType. For instance a string:

/**
* @covers MyClass::Create
* @expectedException Exception
*/
public function testCreate() {
    $myTestedInstance->Create('[email protected]', 'invalid param', ....);
}
Sign up to request clarification or add additional context in comments.

3 Comments

It's worth to add that PHPUnit doesn't let you test against \Exception class. You must use more specialized exception in order to test it (for example: \InvalidArgumentException).
@Cyprian, didnt really get what you are trying to say, pls elaborate with an exception. many thanks
Sure. If you use generic class for throwing exception: \Exception, then PHPUnit test will fail with this message: "InvalidArgumentException: You must not expect the generic exception class.". And this means that you must use more specialized exception class if you want to test exception (eg. \InvalidArgumentException or \LogicException or your own one).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.