0

I want to test a method that can take, as a parameter, either an instance of class Foo or a string. If anything else is passed it throws an Exception.

How do I test that if I don't pass one of the valid types the exception is thrown? How can I make sure that anything other than one of those types will yield an exception?

1
  • Add a call to $this->expectException(WhateverTheException::class) and call your method with the wrong parameter type. Check out phpunit.readthedocs.io/en/8.0/…
    – benJ
    Commented Jun 6, 2019 at 16:15

1 Answer 1

2

To elaborate on my comment on the OP - you can use expectException() to tell PHPUnit that you want to assert that an exception is thrown in the following test. See https://phpunit.readthedocs.io/en/8.0/writing-tests-for-phpunit.html#testing-exceptions

Example:

public function testExceptionIsThrown()
{
    $this->expectException(WhateverTheException::class);

    $class = new ClassToTest;
    $class->methodToTest(1); // an integer is not a string or an instance of Foo and should throw an exception
}
3
  • I know what you mean and my tests are somewhat like that. But what if I pass a float? or a bool? or an instance of some other class? I want to test any other data types. Can it be done? Commented Jun 6, 2019 at 21:22
  • Is that logic in your class method? Something like if (!($value instanceof Foo || is_string($value))) { throw new \Exception('nope'); } If so, you wouldn't really need to test much more. Just a couple of fails and a pass.
    – benJ
    Commented Jun 6, 2019 at 21:28
  • Yes it's something like that. Thanks. Commented Jun 6, 2019 at 21:52

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