用PHPUnit测试error_log [英] testing error_log with PHPUnit

查看:216
本文介绍了用PHPUnit测试error_log的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有要测试的功能,如下所示:

I have this function I want to test looking like this:

class Logger {
  function error($msg){
    if (is_string($msg)){
      error_log($msg);
      die($msg);
    } elseif (is_object($msg)){
      error_log($msg.' '.$msg->getTraceAsString());
      die('exception');
    } else {
      var_dump($msg);
      die('error');
    }
  }

我想在不登录$msg的情况下测试此功能.有没有一种方法可以确定error_log是否在不登录的情况下工作?我尝试使用setExpectedException,但无法捕获该错误,并且一直在记录日志.

I want to test this function without logging the $msg. Is there a way to determine if error_log works without logging? I tried using setExpectedException but I wasn't able to catch the error and it kept logging.

推荐答案

最明显的答案是一个简单的别名/代理函数,该函数本身在Logger类中称为error_log(可以轻松模拟,并检查以了解什么)设置为它),

The obvious answer is a simple alias/proxy-function that itself called error_log in the Logger class (which can be easily mocked, and checked to see what is set to it),

但是要实际测试本地error_log函数(在原始类中没有代理),可以使用名称空间来完成.测试将最终定义为与原始代码相同的名称空间,然后在测试类之后,添加一个函数-在本例中为error_log()-但该函数也在名称空间中定义-因此将在优先于本机功能中等效于root-namespace的计算机.

To actually test the native error_log function however (without a proxy in the original class), can be done with namespaces. The test would end up defined to be the same namespace as the original code, and then after the test class, add a function - in this case error_log() - but that function is also defined in the namespace - and so would be run in preference to the root-namespace-equivalent from the native functions.

很遗憾,您不能对die(或其别名exit)进行相同的覆盖.它们是语言构造",不能像error_log那样被覆盖.

Unfortunately, you can't do the same overriding with die (or its alias, exit). They are 'language constructs', and cannot be overridden like error_log can.

<?php
namespace abc;
use abc\Logger;

class ThreeTest extends \PHPUnit_Framework_TestCase
{
    public function setUp() { $this->l = new Logger(); }
    // test code to exercise 'abc\Logger'

}

// Now define a function, still inside the namespace '\abc'.
public function error_log($msg)
{
   // this will be called from abc\Logger::error
   // instead of the native error_log() function
   echo "ERR: $msg, ";
}

这篇关于用PHPUnit测试error_log的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆