【问题标题】:How to define and code custom unit-test in raw PHP?如何在原始 PHP 中定义和编码自定义单元测试?
【发布时间】:2019-06-19 08:31:35
【问题描述】:

我正在使用一些特殊的 PHP 框架。由于 PHPunit 或 codeception 等原因,我无法使用任何单元测试框架。所以我需要编写我的自定义代码来实现这一点。有什么例子可以完成这项工作吗?

我可以用这个方法代替框架吗?

    public function testFailure()
    {
       $a = 1; $b = 0;
       if($a !=== b){
          //throw exception here
       }
    }

相反-

    public function testFailure()
    {
        $this->assertEquals(1, 0); //return false
    }

【问题讨论】:

    标签: php testing frameworks


    【解决方案1】:

    最简单的方法就是你上面写的(尽管代码不是真的有效)。对断言抛出异常,你就有了一种有效的单元测试方式!

    现在,我认为您可能会使用诸如 phpunit 天气之类的东西,或者您是否正在使用一些自定义代码,但我不会多做这些,只是让您知道。

    还有:

    !=== 无效,!== 会更正确!


    此外,我建议您为 assertions 创建某种类型的静态或全局方法,而不是上面的方法,这样您就可以轻松地重用抛出异常的代码,而不是一遍又一遍地编写相同的代码:

    // assert.php
    class Assert {
      public static function isEqual($a, $b) {
        if ($a != $b) {
          throw new MyAssertionException('Not equal!');
        }
        return true;
      }
    
      public static function isSame($a, $b) {
        if ($a !== $b) {
          throw new MyAssertionException('Not same!');
        }
        return true;
      }
    
    }
    
    ---
    
    // test.php
    include_once 'assert.php';
    
    Assert::isEqual(1, 2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 2014-10-08
      • 2018-02-25
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多