我是 PHPUnit 测试的新手,我想做的是测试一个名为 returnOnLogin()
的方法,该方法接受参数 Enlight_Event_EventArgs $args
并返回 真
。
这是我要测试的方法:
public function returnOnLogin(\Enlight_Event_EventArgs $args)
{
$controller = $args->get('subject');
$view = $controller->View();
$controller->redirect([
'controller' => 'verification'
]);
// $view->addTemplateDir(
// __DIR__ . '/Views'
// );
return true;
}
这是我的测试:
class MyFirstTestPluginTest extends TestCase
{
public function testReturnOnLogin()
{
$my_plugin = new MyFirstTestPlugin(true);
$expected = true;
//I tried following but it did not work
$this->assertEquals($expected, $my_plugin->returnOnLogin(//here is the problem it requires this array that I dont know));
}
最佳答案
假设你的 Controller 类是Controller
,并且假设我们不关心$controller
中调用了view()
,这应该涵盖您正在寻找的内容:
class MyFirstTestPluginTest extends TestCase
{
public function testReturnOnLogin()
{
/**
* create a test double for the controller (adjust to your controller class)
*/
$controller = $this->createMock(Controller::class);
/**
* expect that a method redirect() is called with specific arguments
*/
$controller
->expects($this->once())
->method('redirect')
->with($this->identicalTo([
'controller' => 'verification'
]));
/**
* create a test double for the arguments passed to returnLogin()
*/
$args = $this->createMock(\Enlight_Event_EventArgs::class);
/**
* expect that a method subject() is invoked and return the controller from it
*/
$args
->expects($this->once())
->method('subject')
->willReturn($controller);
$plugin = new MyFirstTestPlugin(true);
$this->assertTrue($plugin->returnOnLogin($args));
}
}
这个测试是做什么的?
安排
此测试首先安排测试替身以用于被测系统(您的插件)。
第一个测试替身是你的 Controller ,我们以这样的方式设置它,即我们期望使用与指定数组相同的参数调用一次方法 redirect()
。
第二个测试替身是参数,我们以这样一种方式设置它,即我们期望方法“subject()”被调用,并将返回 Controller 。
然后,我们设置被测系统,只需创建一个 MyFirstTestPlugin
实例,将 true
传递给构造函数即可。
很遗憾,您没有与我们分享构造函数,我们不知道参数 true
代表什么。如果它影响 returnLogin()
的行为,那么我们显然需要添加更多测试来断言参数采用不同值时的行为。
行动
然后此测试调用被测系统上的方法 returnLogin()
,并传入其中一个测试替身。
断言
最终,此测试断言方法 returnLogin()
返回 true
。
注意看看
关于php - 我如何模拟一个应该接受数组的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037964/