简体   繁体   中英

PHPUnit Exception testing, error message messes up results output

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM