mercredi 30 septembre 2015

How can I force expression given as function parameter to be calculated after the function call?

I am writing my own testing class. The problem I have encountered is testing whether a function being tested throws expected exception.

I know I can do something like this:

try{
  tested_function($expression*$that->will()*$throw->an_exception());
}catch ($exception){
   if($exception instanceof MyExpectedException){
     echo 'OK';
   } else {
     echo 'FAILED';
   }
}

but I'd wish I don't have to write all this try ... catch block everytime, so I want to put it in a tester class method.

But when I do something like this

class Tester {
   /**
    * @param mixed expression to evaluate
    * @param string expected exception class name
    */
   public function assertException($expression, $expectedException){
     try{
       $expression;
     } catch ($ex) {
       if(is_subclass_of($ex, $expectedException)){
         echo 'OK';
       } else {
         echo 'FAILED';
       }
     }

this fails, because $expression is evaluated in the moment of method call, so before the program enters try block.

The other way I tried is to use eval and passing the $expression as a string:

class Tester {
   /**
    * @param string expression to evaluate
    * @param string expected exception class name
    */
   public function assertException($expression, $expectedException){
     try{
       eval($expression);
     } catch ($ex) {
       if(is_subclass_of($ex, $expectedException)){
         echo 'OK';
       } else {
         echo 'FAILED';
       }
     }

This is ok, but it does not allow me to use variables from the main scope, so for example this line fails $test->assertException('$d/0'); because I don't have the $d variable in Tester::assertException() scope.

Should I declare all possible variable names as global?

How can I force the expression to be evaluated within a method (or in other way achieve the desired result)?

I know that there are ready-to-use unit testers (PHPUnit, SimpleTest etc.) but I was desiring to make this myself.

Aucun commentaire:

Enregistrer un commentaire