简体   繁体   English

如何在 PHP (laravel) 中模拟没有类的函数?

[英]How To Mock Functions Without Class in PHP (laravel)?

I have a Function Which is loaded by composer autoload我有一个由 composer autoload 加载的函数

 "autoload": { "files": [ "app/Helpers/SmsHelper.php", ] },

This File Has a smsHelper Function Which Can send SMS.这个文件有一个可以发送短信的 smsHelper 函数。

 <?php if (!function_exists('sendSmsHelper')) { function sendSmsHelper($msisdn, $message) { ..... Codes } }

One Of My class use this Helper and i want to write test for this class.我的一个班级使用这个助手,我想为这个班级编写测试。 could some one tell me how to mock this function?有人可以告诉我如何模拟这个功能吗? because i don't want to send SMS in testing mode因为我不想在测试模式下发送短信

As I dont see any answers I decided to Wrote about some of my researches result: I know these are not the right answers maybe but will work由于我没有看到任何答案,我决定写下我的一些研究结果:我知道这些可能不是正确的答案,但会起作用

First Solution (not good one): if you are using a function in your class and want to writing a test for that class !第一个解决方案(不好的一个):如果您在类中使用一个函数并想为该类编写一个测试! for mocking this type of functions you can set your test class NameSpace equal to the class that you want to writing test for, then you can write a function exactly the same name of specific function out of the class in your .php file.为了模拟这种类型的函数,您可以将您的测试类NameSpace设置为等于您要为其编写测试的类,然后您可以在 .php 文件中的类中编写一个与特定函数完全相同名称的函数。

for example : you use date() in your class and want to mock it to return your String instead of date例如:您在类中使用 date() 并希望模拟它以返回您的字符串而不是日期

 <?php //namespace Tests\\Unit; change this name space to that class you want to write test for namespace yourclass namespace; use Mockery\\Mock; function date() { return "2019/12/17 01:00:00"; } class yourNameTest extends TestCase { ...... you test codes }

Second Solution for the functions you created ( like my smsHelper ) :您创建的功能的第二个解决方案(如我的 smsHelper ):

I added a SwitchCase in my smsHelper function which will check if App is on Testing mode or not , if its on testing mode I'm going to return true;我在我的 smsHelper 函数中添加了一个 SwitchCase,它将检查 App 是否处于测试模式,如果它处于测试模式,我将返回 true;

 function smsHelper() { if (!App::runningUnitTests()) { ....... my codes } else { return true; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM