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.

1
  • 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
    Commented Jul 28, 2017 at 22:47

1 Answer 1

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);
}
2

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