0

I'm trying to test, among others, the constructor of my class. It expects exactly one parameter which has to be a string. So I wrote this test:

class categoryTest extends PHPUnit_Framework_TestCase {

  public function testConstructor() {

    $this->setExpectedException('Exception', 'Unknown data type.');
    $objCategory = new category(1);

    $this->setExpectedException('Exception', 'Unknown data type.');
    $objCategory = new category(-500);

    $this->setExpectedException('Exception', 'Unknown data type.');
    $objCategory = new category(true);

    $this->setExpectedException('Exception', 'Unknown data type.');
    $objCategory = new category(array());

    ...

  }

  public function testNextMethod() {

  }

}

As you can see, I expect each time the same exception.

This works very well, so it seems, but the script will skip to testNextMethod() after finishing

$this->setExpectedException('Exception', 'Unknown data type.');
$objCategory = new category(1);

. Do I have to write for each test an own testMethod()? Or is there any workaround?

Best regards, muff

EDIT:

Hello Cyprian,

thank you very much for your response. I solved my problem like this:

class categoryTest extends PHPUnit_Framework_TestCase {

    protected $backupGlobals = FALSE;

    /**
      *
      * @dataProvider provider
      *
      **/
    public function testMuff($strCategory) {

      $this->setExpectedException('Exception', 'Unknown data type.');
      $objCategory = new category($strCategory);

    }

    public function provider() {

      $objHIS = new DDDBL('HIS');

      return array(array(1),
                   array(-500),
                   array(true),
                   array(array()),
                   array($objHIS)
                  );

    }

    ...

}

Now it works perfectly, even if I don't like the notation at all.

1
  • "Note : You should be as specific as possible when testing exceptions. Testing for classes that are too generic might lead to undesirable side-effects. Accordingly, testing for the Exception class with @expectedException or setExpectedException() is no longer permitted.". Source : phpunit.de/manual/current/en/writing-tests-for-phpunit.html Commented Jan 17, 2018 at 9:38

1 Answer 1

1

The thing you are looking for is DataProvider, look here:

http://www.phpunit.de/manual/3.6/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers

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

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.