在PHPUnit测试中,有什么方法可以“期望"输出到error_log? [英] Is there any way to 'expect' output to error_log in PHPUnit tests?

查看:114
本文介绍了在PHPUnit测试中,有什么方法可以“期望"输出到error_log?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用phpunit进行单元测试时,是否有任何方法可以对通过调用'error_log("Message")'创建的输出进行测试?

Is there any way to run a test on output created from a call to 'error_log("Message")' when doing unit tests with phpunit?

示例代码,我的功能之一是使用luhn算法测试信用卡:

Example code, one of my functions tests a credit card with a luhn algorithm:

if($checkLuhn && ($this->_luhn_check($cardNumber) == false)) {
    error_log(__METHOD__ . " cardNumber failed luhn algorithm check.");
    return false;
}

$ checkLuhn是一个布尔值,用于告知是否执行检查,如果$ cardNumber通过,则_luhn_check()返回true.问题是,我在此函数中有多个测试可以返回false.我可以在返回值上使用assertEquals,但是还想检查为什么会引发错误.

$checkLuhn is a boolean passed in to tell it whether to do the check, the _luhn_check() returns true if the $cardNumber passes. Problem is, I have more than one test in this function that can return false. I can use assertEquals on the return value, but also want to check why the error was thrown.

您是否可以覆盖error_log或以某种方式在单元测试中获取syslog输出?

Can you override error_log or otherwise grab syslog output in a unit test somehow?

推荐答案

有几种不同的方法可以指示error_log()发送数据的位置.

There are a few different ways to direct where error_log() sends data.

首先要像error_log()一样将其发送到其他地方.一个例子是:

First is to just as error_log() to send it some where else. An example would be:

error_log( 'This is a message from error_log()', 3, '/dev/stdout' );

为error_log()使用目标选项.

That uses the destination option for error_log().

另一种方法是覆盖 error_log ini设置PHP .看起来像这样:

Another approach is to override the error_log ini setting in PHP. That would look something like:

$cur_error_log = ini_get( 'error_log' );
ini_set( 'error_log', '/dev/stdout' );
error_log( 'This is a message from error_log()' );
ini_set( 'error_log', $cur_error_log );

在这两个选项中,我通常倾向于尽可能在error_log()中使用目标选项.

Of the two options I generally prefer using the destination option in error_log() when possible.

从那里,您可以使用PHPUnit中的ExpectOutputString()查找从error_log()发送的数据.

From there you could use expectOutputString() from PHPUnit to look for the data sent from error_log().

这篇关于在PHPUnit测试中,有什么方法可以“期望"输出到error_log?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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