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
    – Mark Baker
    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?
    – neubert
    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');
 }
1
  • It's not :( I'm running phpunit 4.4.0. Maybe that's not the version I need to be running?
    – neubert
    Commented Dec 18, 2014 at 20:23
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');

}

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