Duru Can Celasun
Duru Can Celasun

Reputation: 1681

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

Assume I have the following class:

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

Now, in a 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? Why? Why not?

Upvotes: 4

Views: 879

Answers (1)

edorian
edorian

Reputation: 38961

If you are using the same code with different data set and you are expecting similar output you can use the dataProvider() feature

Example adapted from the 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 having multiple tests is preferable as you can use the proper assert[Xml/Json]StringMatches() functions and you get better error output.

For additional error checks I'd recommend adding more test methods:

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

Upvotes: 7

Related Questions