Php 为Silex应用程序分配属性以进行单元测试
我正在尝试对Silex应用程序进行单元测试。 这是我正在测试的代码:Php 为Silex应用程序分配属性以进行单元测试,php,phpunit,silex,Php,Phpunit,Silex,我正在尝试对Silex应用程序进行单元测试。 这是我正在测试的代码: use Silex\Application; class MyUser { public function run(Application $app) { // show what $app['env'] actually contains var_dump($app['env']); if ($app['env'] == 'prod') {
use Silex\Application;
class MyUser
{
public function run(Application $app)
{
// show what $app['env'] actually contains
var_dump($app['env']);
if ($app['env'] == 'prod') {
return true;
} else {
return false;
}
}
}
我参加了以下的测试课程:
class TestMyUser extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->app = $this->getMockBuilder('\Application')
->disableOriginalConstructor()
->getMock();
$this->myUser = new MyUser();
}
public function testRun()
{
$this->app['env'] = 'prod'; // this outputs NULL
$this->app->env = 'prod'; // this outputs NULL
$this->values['env'] = 'prod'; // this throws an error saying that values is a protected property
$result = $this->myUser->run($this->app);
$this->assertEquals(true, $result); // will always fail as $app['env'] is NULL
}
}
我似乎不知道如何为模拟应用程序分配属性。
有人有想法吗?让“值”模拟属性可访问:
public function testRun()
{
$reflection = new ReflectionClass($this->myUser);
$reflection_property = $reflection->getProperty('values');
$reflection_property->setAccessible(true);
$values = $reflection_property->getValue('values');
$values['env'] = 'prod';
$reflection_property->setValue('values', $values);
$result = $this->myUser->run($this->app);
$this->assertEquals(true, $result); // will always fail as $app['env'] is NULL
}
我自己刚吃过这个。当您按照代码示例创建该模拟时,它不会实现应用程序的任何方法。如果希望方法仍存在于模拟中,则需要调整模拟,如下所示:
$this->app=$this->getMockBuilder(“\Application”)
->disableOriginalConstructor()
->setMethods(null)//您需要这个
->getMock();
给予null
将意味着不模仿它的任何方法。我原以为根本不调用setMethods
也会有同样的效果,但是:不
执行此操作时:
$this->app['env']='prod';
它正在调用应用程序的方法,因此该方法必须存在。这不起作用。对于$app['env'],我仍然得到空值。我不认为更改反射类的“values”属性最终会更改模拟的应用程序对象。您实际上是通过使用反射类来更改应用程序对象。但可能它在模拟对象中不起作用。