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?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Gonçalo Marrafa
  • 2,013
  • 4
  • 27
  • 34
  • Add a call to `$this->expectException(WhateverTheException::class)` and call your method with the wrong parameter type. Check out https://phpunit.readthedocs.io/en/8.0/writing-tests-for-phpunit.html#testing-exceptions – benJ Jun 06 '19 at 16:15

1 Answers1

1

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
}
benJ
  • 2,442
  • 1
  • 18
  • 16
  • 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? – Gonçalo Marrafa Jun 06 '19 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 Jun 06 '19 at 21:28
  • Yes it's something like that. Thanks. – Gonçalo Marrafa Jun 06 '19 at 21:52