Function 跳过代码行&;测试时在PHPUnit内的公共函数内设置变量
我肯定以前也有人问过类似的问题,但我读过好几个论坛,还没有找到解决办法。我正在使用PHPUnit版本3.7.38,如果这有什么不同的话 我正在测试一个函数Function 跳过代码行&;测试时在PHPUnit内的公共函数内设置变量,function,unit-testing,phpunit,code-coverage,Function,Unit Testing,Phpunit,Code Coverage,我肯定以前也有人问过类似的问题,但我读过好几个论坛,还没有找到解决办法。我正在使用PHPUnit版本3.7.38,如果这有什么不同的话 我正在测试一个函数 public function someFunction() { $variable2 = Input::get('someValue'); if (strlen($variable2) == 0) { return Redirect::to('/somepage')
public function someFunction()
{
$variable2 = Input::get('someValue');
if (strlen($variable2) == 0) {
return Redirect::to('/somepage')->with(
'notification',
array(
'type' => 'danger',
'text' => 'text.'
)
);
}
...More Code that needs to be tested
我的问题是,每次PHPUnit运行时,$variable2都返回null,因为它无法获取someValue。代码返回并跳过函数的其余部分。我想跳过$variable2的声明,将其赋值给strlen()大于零的值,这样测试就覆盖了函数的其余部分。有办法做到这一点吗
我已经阅读了PHPUnit网站上关于忽略代码块的文档,但是没有任何运气。也许我没有实现
/**
* @codeCoverageIgnore
*/
正确地说,或者说,这甚至不是CodeCoverGeignore的本意。我试着将@codeCoverage放在我正在测试的实际代码中,但我也不认为这是正确的,因为我仍然想测试if分支,如果它是真的。我认为您也不必为了测试而编辑正在测试的代码
@CodeCoverageIgnore
这用于告诉代码覆盖率计算跳过此部分,不将其包括在测试覆盖率计算中。因此,该模块不包括在测试覆盖/未覆盖线的计数中
但是,您确实需要处理Input::方法并对其进行设置。最好的方法是重构代码,将输入例程移出,由依赖项注入提供,然后允许您模拟输入例程来设置文本字符串,并允许测试继续
class ToTest
{
private $InputObject
public function __construct($Input = NULL)
{
if(! is_null($Input) )
{
if($Input instanceof Input) // The class that you were referencing Input::
{
$this->SetInput($Input);
}
}
}
public function SetInput(Input $Input)
{
$this->InputObject = $Input
}
public function someFunction()
{
$variable2 = $this->InputObject::get('someValue');
if (strlen($variable2) == 0) {
return Redirect::to('/somepage')->with(
'notification',
array(
'type' => 'danger',
'text' => 'text.'
)
);
}
...More Code that needs to be tested
}
}
测试:
谢谢我正在使用Laravel4并尝试这样做,但无法模拟输入类。它返回不能重新声明mockry\u 30\u lighting\u Support\u Facades\u Input::shouldReceive()。我不知道为什么它试图重新声明应该接收,。我看到另一个论坛并尝试了\illustration\Http\Request,但最终出现了嵌套级别为“100”的错误。我不使用Laravel,但可能会在他们的论坛上发布更详细的问题,甚至在这里发布关于堆栈溢出的问题,您可能会得到直接的答案。
class InputTest extends PHPUnit_Framework_TestCase
{
// Simple test for someFunctione to work Properly
// Could also use dataProvider to send different returnValues, and then check with Asserts.
public function testSomeFunction()
{
// Create a mock for the Your Input class,
// only mock the someFunction() method.
$MockInput = $this->getMock('YourInput', array('someFunction'));
// Set up the expectation for the someFunction() method
$MockInput->expects($this->any())
->method('get')
->will($this->returnValue('Test String'));
// Create Test Object - Pass our Mock as the Input
$TestClass = new ToTest($MockInput);
// Or
// $TestClass = new ToTest();
// $TestClass->SetInput($MockInput);
// Test someFunction
$this->assertEquals('Test String', $TestClass->someFunction());
}
}