2

My phpunit test:

<?php
class TestTest extends PHPUnit_Framework_TestCase
{
        /*
         * @expectedExceptionMessage success
         */
    public function testExceptionMessage() {
        throw new Exception('success');
    }
}

The unit test is failing. Here's the output of phpunit:

There was 1 error:

1) TestTest::testExceptionMessage
Exception: success

/path/to/TestTest.php:8

FAILURES!                          
Tests: 1, Assertions: 0, Errors: 1.

It seems to me that the test ought to be a success since the Exception message is success, which is what @expectedExceptionMessage is expecting?

4
  • Would you ever need to do this? Surely you would be testing if a piece of code throws an exception, not the test itself. Commented Dec 18, 2014 at 17:10
  • Add an annotation for @expectedException Exception.... @expectedExceptionMessage works in conjunction with @expectedException Commented Dec 18, 2014 at 17:12
  • @David Jones - it's just a demo. Would you rather I post a multi-MB code base with a whole lot of unit tests and say "why isn't it working??" or would you rather I isolate the problem as much as I possibly can and then post? Commented Dec 18, 2014 at 18:42
  • Not at all, but the code sample in the question made it look like you were throwing the exception in the test which was the source of my confusion Commented Dec 18, 2014 at 22:22

2 Answers 2

5

Add the @expectedException annotation and it should work

/**
 * @expectedException Exception
 * @expectedExceptionMessage success
 */
 public function testExceptionMessage() {
    throw new Exception('success');
 }
Sign up to request clarification or add additional context in comments.

1 Comment

It's not :( I'm running phpunit 4.4.0. Maybe that's not the version I need to be running?
2

You need to alert PHPUnit BEFORE throwing it:

  1. to expect the exception
  2. to expect the specific message you're throwing.
 public function testExceptionMessage() {

    $this->expectException(Exception::class);  
    $this->expectExceptionMessage('success');
 
    throw new Exception('success');

}

Comments

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.