沃梦达 / 编程问答 / php问题 / 正文

使用 PHPUnit 测试 error_log

testing error_log with PHPUnit(使用 PHPUnit 测试 error_log)

本文介绍了使用 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');
    }
  }

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.

解决方案

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),

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.

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 abcLogger;

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

}

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

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

本文标题为:使用 PHPUnit 测试 error_log

基础教程推荐