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?
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.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With