PHPUnit:如何测试调用在不同文件中声明的另一个函数的方法 [英] PHPUnit: How to test a method which calls another function declared in different file

查看:147
本文介绍了PHPUnit:如何测试调用在不同文件中声明的另一个函数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHPUnit测试一种方法,该方法将调用另一个函数(独立函数,不带类),该函数驻留在不同的文件中,该文件进行了一些很好的计算并返回了一个对象

I'm trying to test a method using PHPUnit, where it calls another function (standalone function, without class), which resides in different file which does a some pretty good calculation and returns a object.

这是我实际的主要代码:

This is my actual main code:

class CreateRecords
{
    public function createEntities($details)
    {
        if (trim($details['username']) == "") {
            $this->result = "Username is empty.";
        } else {
            $this->result = create_record($Details['username']);
        }       
        return $this->result;
    }
}

create_record函数(独立函数,不带类)是核心函数,驻留在单独的文件中,并且能很好地进行计算(调用许多其他方法/函数)并返回对象,无论对象是否成功.

This create_record function, (standalone function, without class), which is core function, resides in separate file and it does pretty good calculations (calls lots of other methods/functions) and returns object, whether it is successful or not.

我可以模拟createEntities方法,但是我想模拟create_record函数,该函数执行所有计算并返回结果.

I can mock the createEntities method, but I want to mock the create_record function, which does all the computations and returns the result.

我看到过几处场景类似的帖子,

I have seen few posts which has a somewhat similar scenario,

调用其他类的phpunit测试方法需要模拟的方法

另一个类中使用的PHPUnit模拟方法

但是我不明白如何模拟在其他文件中声明的独立函数.

But I am unable to understand, how to mock standalone function which is declared in some different file.

推荐答案

您可以创建将从外部函数返回结果的新方法. 然后您可以模拟这个新方法

You can create new method that will be returning result from outside function. Then you can mock this new method

class CreateRecords
{
    public function createEntities($details)
    {
        if (trim($details['username']) == "") {
            $this->result = "Username is empty.";
        } else {
            $this->result = $this->createRecord($Details['username']);
        }       
        return $this->result;
    }

    public function createRecord($username){
    return create_record($username);
    }
}

这篇关于PHPUnit:如何测试调用在不同文件中声明的另一个函数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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