Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i unit test for invalid arguments with phpunit?

I'm just learning unit testing. This php code

class Foo {
    public function bar($arg) {
        throw new InvalidArgumentException();
    }
}

...

class FooTest extends PHPUnit_Framework_TestCase {
    public function testBar() {
        $this->setExpectedException('InvalidArgumentException');
        $dummy = Foo::bar();
    }
}

fails with Failed asserting that exception of type "PHPUnit_Framework_Error_Warning" matches expected exception "InvalidArgumentException". from phpunit. If any value is placed within the Foo::bar() test then it, of course, works as expected. Is there a way to test for empty arguments? Or am I erroneously trying to create a test for something that shouldn't be within the scope of a unit test?

like image 882
Isius Avatar asked Feb 19 '23 03:02

Isius


2 Answers

You shouldn't test such situations. A purpose of a unit test is to make sure that a class under test performs according to its "contract", which is its public interface (functions and properties). What you're trying to do is to break the contract. It's out of scope of a unit test, as you said.

like image 137
yegor256 Avatar answered Mar 02 '23 17:03

yegor256


I agree with 'yegor256' in the testing of the contract. However, there are times where we have arguments that are optional, to use previously declared values, but if they are not set, then we throw exceptions. A slightly modified version of your code (simple example, not good or production ready) is shown below with the tests.

class Foo {
    ...
    public function bar($arg = NULL)
    {
        if(is_null($arg)        // Use internal setting, or ...
        {
                  if( ! $this->GetDefault($arg)) // Use Internal argument
                  {
                       throw new InvalidArgumentException();
                  }
        }
        else
        {
            return $arg;
        }
    }
}

...
class FooTest extends PHPUnit_Framework_TestCase {
    /**
     * @expectedException InvalidArgumentException
     */
    public function testBar() {
        $dummy = Foo::bar();
    }

    public function testBarWithArg() {
        $this->assertEquals(1, Foo:bar(1));
    }
}
like image 22
Steven Scott Avatar answered Mar 02 '23 17:03

Steven Scott