How do I unit test for invalid arguments with phpunit?

I am 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(); } } 

does not work with Failed asserting that exception of type "PHPUnit_Framework_Error_Warning" matches expected exception "InvalidArgumentException". from phpunit. If any value is in the test Foo::bar() , then of course it works as expected. Is there any way to check for empty arguments? Or am I mistakenly trying to create a test for something that should not be within the unit test?

+4
source share
2 answers

You should not check such situations. The purpose of the unit test is to make sure that the class under test works in accordance with its β€œcontract”, which is its public interface (functions and properties). What you are trying to do is break the contract. As you said, this is beyond the scope of unit test.

+6
source

I agree with "yegor256" when testing the contract. However, there are times when we have arguments that are optional for using previously declared values, but if they are not set, then we throw exceptions. Below is a small version of your code (a simple example, not good or ready for production).

 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)); } } 
+2
source

Source: https://habr.com/ru/post/1434665/


All Articles