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

user2909892
  • 235
  • 3
  • 11
  • 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 – user2909892 Nov 03 '13 at 09:43
  • How is that not a duplicate? – hakre Nov 03 '13 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? – vascowhite Nov 03 '13 at 16:00

1 Answers1

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@example.com', 'invalid param', ....);
}
Jardo
  • 1,939
  • 2
  • 25
  • 45
  • 1
    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 Nov 02 '13 at 11:12
  • @Cyprian, didnt really get what you are trying to say, pls elaborate with an exception. many thanks – user2909892 Nov 03 '13 at 09:25
  • 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). – Cyprian Nov 03 '13 at 10:48