PHPUnit测试一个函数被调用多少次 [英] PHPUnit Test How Many Times A Function Is Called

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

问题描述

我正在phpunit中进行测试,但遇到了问题.我在课堂上尝试测试一个公共功能.根据传递给方法的参数,同样在我的测试类中的受保护函数将被调用一两次.目前,我已经进行了一项测试,以检查返回的数据是否正确,但是我还想确保被保护的方法被调用了正确的次数.

I'm working on a test in phpunit and I'm running into an issue. I have a public function on my class that I am trying to test. Depending on the parameters passed in to the method, a protected function also in my test class will be called one or two times. I currently have a test in place to check that the return data is correct, but I would also like to make sure the protected method is being called the correct number of times.

我知道一个模拟对象可以让我计算一个函数被调用的次数,但是它也会覆盖受保护函数返回的值.我尝试使用没有"will"部分的模拟对象,但它只会返回null,而不是受保护方法的实际值.

I know that a mock object will allow me to count the number of times a function is called, but it will also override the value returned by the protected function. I tried using a mock object with no "will" section, but it would just return null, not the actual value for the protected method.

ExampleClass

ExampleClass

public function do_stuff($runTwice){
$results = do_cool_stuff();
  if($runTwice){
    $results = 2 * do_cool_stuff();
  }
  return $results;
}

protected function do_cool_stuff()
{
  return 2;
} 

在测试中,我想检查do_cool_stuff()是被调用一次还是两次,但是我仍然希望两个函数的返回值都相同,因此我也可以在单元测试中对其进行测试.

In my test, I want to check whether do_cool_stuff() was called once or twice, but I still want the return values of both functions to be the same so I can test those as well in my unit test.

tl;博士 我想计算测试对象中受保护的方法被调用的次数(就像您可以对模拟对象执行的操作一样),但是我仍然希望测试方法中的所有方法都返回其正常值(不像模拟对象)

tl;dr I want to count the number of times a protected method in my test object is called (like you can do with a mock object) but I still want all the methods in my test method to return their normal values (not like a mock object).

推荐答案

在使用该类之前尝试设置全局变量.

Try setting a global variable prior to utilizing the class.

$IAmDeclaredOutsideOfTheFunction;

然后使用它来存储计数,并在调用函数和类之后简单地对其进行检查.

then use it to store the count and simply check it after your functions and classes have been called.

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

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