3

I can't seem to correctly do this, the error message of the exception just prints out, making the command line window harder to read. Below is how my code is structured and the test code.

public function availableFruits($fruit)
{
  switch($fruit) {
    case 'foo':
    // all good
    break;

    case 'bar':
    // all good
    break;

    default:
    throw new Exception($fruit.' not available!');
    break;

  }
}

public function chooseFruit($fruit)
{
  try {
    availableFruits($fruit);
  } catch (Exception $e) {
    echo $e->getMessage();
  }
}

public function testAvailableFruits()
{
  $this->setExpectedException('Exception');

  chooseFruit('Kiwi');
}

The error message will print out in the command line window like below. I tried all the methods shown in phpunit.de but same results.

..Error on line 13 in c:\file\path\fruits.php: Kiwi not available!.F

The error line prints out, how do I suppress that, am I doing it right at all?

1
  • this is a php bug. trying to instantiate a new class results in a exception trhown in the parser, so it messes up things. i don't know about the expectedException in phpuni as this is not available on the stable version i'm using via ubuntu repositories. Commented May 30, 2011 at 19:54

2 Answers 2

4

I believe another way to do it is to add a comment block to the test method that looks like...

/**
 * @expectedException ExpectedExceptionName
 */

Or, you can also catch the exception your self cause the method to fail if you don't get inside the catch block.

Sign up to request clarification or add additional context in comments.

Comments

1

This is embarrassing as I found just the way to do it. Thanks Chris, but I tried that as well.

I tested the wrong method, chooseFruit isn't the method that throws the exception, so the exception error prints out:

public function testAvailableFruits()
{
  $this->setExpectedException('Exception');
  **chooseFruit('Kiwi');**
}

Testing the actual method that throws the exception will mute the error message, since it is not echoed at all:

public function testAvailableFruits()
{
  $this->setExpectedException('Exception');
  **availableFruits('Papaya')**
}

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.