PHPUnit中使用shouldReceive进行随机输入的模拟方法

时间:2015-03-03 22:25:13

标签: php unit-testing laravel-4 phpunit mockery

我正在使用Laravel 4和PHPUnit 3.7.38。我有一个使用随机生成的值进行输入的类。我使用str_random(100)。我想对它进行单元测试;但是,每次,我尝试在方法上使用shouldReceive,我得到一个错误,说该值与预期值不匹配。这是有道理的,因为它在测试之前随机生成值。我不能重构原始代码,我不能抛出异常停止代码,因为在同一个函数中有更多的代码来测试。我试过模拟str_random函数;然而,这会引发另一个错误。我真的不确定该做什么,或者目前是否有一个好的解决方案。我的代码如下:

class OriginalClass {

public function someFunction{

$randomCode = str_random(100);

    anotherFunction(array($name, $lastName, $randomCode), $anotherValue)

    }

}



class OriginalClassTest {



        $this->MockObject
            ->shouldReceive('anotherFunction')
            ->with(array('Jon', 'Smith', '11155488321'), '49')
            ->andReturn('Output');

        $this->assertEquals('Output', $this
            ->MockObject
            ->anotherFunction(array('Jon', 'Smith', '11155488321'), '49')); 
}

当调用该函数时,已经创建了一个新生成的$ randomCode,我得到了错误

"Mockery\Exception\NoMatchingExpectationException : No matching handler found for Mockery_1_MockObject::anotherFunction(array('Jon', 'Smith', 'newly generated randomCode'), '49')"

1 个答案:

答案 0 :(得分:0)

您没有测试str_random功能。所以你的测试用简单的英语写成:

  

str_random返回" ABCD"时,"另一个功能"应该用" ABCD"作为$randomCode参数。

换句话说,您需要控制测试中的随机字符串,并确保在调用其他函数时使用该值。你可以通过使用一个类来提供随机字符串,并在类中模拟它,或者使用像this one这样的其他技巧。

如果你已经尝试过并收到错误,请发布错误,以便我们为您提供帮助。