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. 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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

You can also use annotations for that, see as well: phpunit.de/manual/current/en/writing-tests-for-phpunit.html and other examples, like Q&A here on site: stackoverflow.com/a/39837176/367456
@LeeJ It is not necessary to add $this->expectException('Exception'); to test the the exception message, there were an issue filled about that and it is now solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.