【问题标题】:How to test this code in Phpunit如何在 Phpunit 中测试此代码
【发布时间】:2014-03-15 23:30:01
【问题描述】:

我是测试的初学者。 有一个应用程序。使用 singelton(方法 A :: getMainApp () 将返回到应用程序)。 在测试类中有一个方法:

protected function endApp ()
{
    $ logger = new MainLogger ();
    $ logger-> log ();

    $ this-> response-> send ();
    exit ( 0);
}

此方法使用两个类(MainLogger、ResponseManager ($ this-> response)),而后者甚至可能使用其他类。

在这个测试中,我不需要“模拟和创建”所有必需的类吗? 我基本上需要测试所谓的log (), response-> send () and exit ( 0) 他们的结果我会检查我何时分别测试每个类以及何时在“浏览器级别”测试应用程序对吗?

如何验证该方法以正确的顺序准确地诱导出所需的功能? 我知道我不能使用模拟对象,因为我使用单格?

谢谢。

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

    您的问题是您的类与MainLogger 和ResponseManager 紧密耦合,您无法模拟它们,因此您无法单独测试您的方法。需要进行一些重构。

    我不知道你的类是怎么写的,但是你需要像这样注入依赖来使它可测试。将它们传递给构造函数是一种方法。这样你就可以传入一个模拟对象来进行测试。

    或者,您可以将依赖项传递给需要它们的方法,例如:-

    protected function endApp(MailLogger $logger)
    {
        $ logger->log();
    
        $ this->response->send();
        exit(0);
    }
    

    附带说明;我不确定你想在这里exit(),因为这会完全停止你的脚本,我认为return 会更合适。

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 1970-01-01
      • 2013-11-10
      • 2011-04-16
      • 1970-01-01
      • 2017-11-19
      • 2023-04-01
      • 2021-02-08
      • 2013-10-01
      相关资源
      最近更新 更多