1

Looking for some help to write better code /tests, but seemed to have stumbled across a problem straight away - any help would be greatly appreciated.

Script:

$feed = 'App\Http\Services\Supplier\Feeds\\' . ucwords($feedName) . "Feed";

if (class_exists($feed)) {
    return new $feed($headerRowToSkip);
} else {
    throw new Exception("Invalid feed type given.");
}

Test:

 public function testBuild()
{
    SupplierFeedFactory::build('MusicMagpie', 1);
    $this->expectExceptionMessage("Invalid feed type given.");
}

Error:

There was 1 failure:

1) Tests\Feature\Account\Supplier\Feeds\SupplierFeedFactoryTest::testBuild Failed asserting that exception of type "Exception" is thrown.

hakre
  • 193,403
  • 52
  • 435
  • 836
LeeJ
  • 137
  • 1
  • 12
  • The expectations must be expressed before the tested code. Otherwise, they are useless. It's like you are buying an umbrella after the rain stopped. In your case, the line that calls `$this->expectExceptionMessage()` doesn't run because (what else?) the tested code (`SupplierFeedFactory::build()`) has thrown an exception. – axiac Jul 28 '17 at 22:47

1 Answers1

3

The PHPUnit method is literal, EXPECTexception so all you have to do is put that before the exception actually happens.

public function testBuild()
{
    $this->expectException('Exception');
    $this->expectExceptionMessage("Invalid feed type given.");
    SupplierFeedFactory::build('MusicMagpie', 1);
}
LeeJ
  • 137
  • 1
  • 12
  • You can also use annotations for that, see as well: https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html and other examples, like Q&A here on site: https://stackoverflow.com/a/39837176/367456 – hakre Jul 28 '17 at 22:44
  • @LeeJ It is not necessary to add `$this->expectException('Exception');` to test the the exception message, there were an [issue](https://github.com/sebastianbergmann/phpunit/issues/2299) filled about that and it is now solved. – H Aßdøµ May 08 '20 at 13:51