PHPUnit: What is the best way to test a function with multiple datasets?

Suppose I have the following class:

class Foo { static function bar($inputs) { return $something; } } 

Now in the test class I have the following structure:

 class FooTest extends PHPUnit_Framework_TestCase { function testBar() { $result = Foo::bar($sample_data_1); $this->assertSomething($result); $result = Foo::bar($sample_data_2); $this->assertSomething($result); $result = Foo::bar($sample_data_3); $this->assertSomething($result); } } 

Is this a good structure? Should I divide testBar() into 3 separate functions? What for? Why not?

+4
source share
1 answer

If you use the same code with a different data set and you expect similar output, you can use the dataProvider() function

Example adapted from PHPUnit docs:

 <?php class DataTest extends PHPUnit_Framework_TestCase { /** * @dataProvider provider */ public function testAdd($sample, $data, $result) { $this->assertEquals($result, Foo::bar($sample, $data); } public function provider() { return array( array(0, 0, 0), array(0, 1, 1), array(1, 0, 1), array(1, 1, 3) ); } } 

if you have completely different return values ​​/ structures, for example, it returns XML and JSON depending on the input, then it is preferable to use several tests, since you can use the correct assert[Xml/Json]StringMatches() functions, and you will get the best error result.

For additional error checks, I would recommend adding additional testing methods:

 /** * @expectedException InvalidArgumentException */ public function testError() { Foo::bar("invalidArgument"); } 
+6
source

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


All Articles