views:

434

answers:

2

Hi, my question regarding phpunit for testing exceptions using the command line tool. 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?

Thanks!

A: 

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.

Chris Gutierrez
A: 

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')**
}
Edward