以SilexApplication为参数的单元测试方法


Unit test method with SilexApplication as parameter

在我的项目中,我有一个类SessionManager,它为粘性表单等设置和清除会话变量。该类中的每个方法都接受一个Silex''Application对象作为参数。如何对这些方法进行单元测试?在每个测试方法中创建一个Silex应用程序对象?我是Silex和单元测试的新手,所以不知道如何处理这个问题。

一种方法的示例:

public static function setMessage($message, $messageClass, Application &$app)
{
    // store message as array, with content and class keys
    $app['session']->set('message', array(
        'content' => $message,
        'class' => $messageClass
    ));
}

首先,我认为$app不应该是SessionManager的依赖项;$app['session']应该是。但它也应该是对象的依赖项(即:传递给构造函数),而不是单个方法的依赖项。

但这并不能改变解决问题的策略。您所需要做的就是创建会话的模拟,它涵盖了您需要调用的依赖方法,例如:

// in your test class
// ...
public function setup(){
    $mockedSession = $this->getMockedSession();
    $this->sessionManager = new SessionManager($mockedSession);
}
public function testMessage(){
    // test stuff here
}
private function getMockedSession(){
    $mockedSession = $this->getMockBuilder(''Symfony'Component'HttpFoundation'Session'Session')
        ->disableOriginalConstructor()
        ->setMethods(['set'])
        ->getMock();
    $mockedSession->method('set')
        ->willReturn('something testable');
    return $mockedSession;
}

您可能只需要测试setMessage方法是否通过其$message$messageClass值传递到模拟方法:这就是它所做的全部工作。在这种情况下,你可能也想在你的模型中有一个->with('message', [$testMessage, $testClass])或其他东西。具体的实现取决于您想要如何进行测试。