测试几种方法来正确验证传递的参数

时间:2013-07-23 14:04:33

标签: phpunit

我有几个方法使用相同的参数(user_id)。在这些方法中,我测试传递有效八位数整数的参数。 是否有可能将(?)test(s)用于测试传递参数的验证?

Class Hello{
public function test($user_id=0){
 if (!preg_match('/^[0-9]{8}$/', $user_id)) return false;
do stuff...
}
public function make($user_id=0){
 if (!preg_match('/^[0-9]{8}$/', $user_id)) return false;
do stuff...
}
public function find($user_id=0){
 if (!preg_match('/^[0-9]{8}$/', $user_id)) return false;
do stuff...
}
}

和测试文件:

class HelloTest extends PHPUnit_Framework_TestCase {

//Looking for something simpler to replace that:
        // zwraca FALSE jesli dlugosc inna niz 8 znakow 
        $this->assertFalse(Hello::test('1'), 'Dlugosc user_id musi byc 8 znakow, nie 1.');
        $this->assertFalse(Hello::test(0), 'Dlugosc user_id musi byc 8 znakow, nie 1 (zero).');
        $this->assertFalse(Hello::test('7777777'), 'Dlugosc user_id musi byc 8 znakow, nie 7.');

        $this->assertFalse(Hello::make('1'), 'Dlugosc user_id musi byc 8 znakow, nie 1.');
        $this->assertFalse(Hello::make(0), 'Dlugosc user_id musi byc 8 znakow, nie 1 (zero).');
        $this->assertFalse(Hello::make('7777777'), 'Dlugosc user_id musi byc 8 znakow, nie 7.');

        $this->assertFalse(Hello::find('1'), 'Dlugosc user_id musi byc 8 znakow, nie 1.');
        $this->assertFalse(Hello::find(0), 'Dlugosc user_id musi byc 8 znakow, nie 1 (zero).');
        $this->assertFalse(Hello::find('7777777'), 'Dlugosc user_id musi byc 8 znakow, nie 7.');
}

1 个答案:

答案 0 :(得分:1)

PHPUnit Manual, under Data Providers中,您可以使用数据提供程序将值传递给测试。我这样做,并包括预期的响应值。

<?php
class HelloTest extends PHPUnit_Framework_TestCase
{
    public function UserIdDataProvider()
    {
        return array(
            array('1', FALSE, 'Dlugosc user_id musi byc 8 znakow, nie 1.'),
            array(0, FALSE, 'Dlugosc user_id musi byc 8 znakow, nie 1 (zero).'),
            array('7777777', FALSE, 'Dlugosc user_id musi byc 8 znakow, nie 7.'),
            array('88888888', TRUE, ''),
        );
    }

     /**
     * @dataProvider UserIdDataProvider
     */
    public function testUserIdTest($UserId, $Result, $Message)
    {
        $this->assertEquals($Result, Hello::test($UserId), $Message);
    }

    /**
     * @dataProvider UserIdDataProvider
     */
    public function testUserMake($UserId, $Result, $Message)
    {
        $this->assertEquals($Result, Hello::make($UserId), $Message);
    }

    /**
     * @dataProvider UserIdDataProvider
     */
    public function testUserIdFind($UserId, $Result, $Message)
    {
        $this->assertEquals($Result, Hello::find($UserId), $Message);
    }

}
?>