我最近在学习Symfony 3框架和依赖注入.
我希望您帮助我解决我对使用PHPUnit在Symfony 3 中测试服务的方法的疑虑.我有一些担心如何正确地做到这一点.
让我们举一个Service类的例子:
// src/AppBundle/Services/MathService.php
namespace AppBundle\Services;
class MathService
{
public function subtract($a, $b)
{
return $a - $b;
}
}
Run Code Online (Sandbox Code Playgroud)
我看到通常Symfony中的UnitTest类测试控制器.
但是,我可以测试像服务这样的独立类(例如包含业务逻辑)而不是控制器?
我知道至少有两种方法可以做到:
1.创建一个测试类,在此测试类中的某些方法或构造函数中扩展PHPUnit_Framework_TestCase和创建 Service对象(与Symfony关于测试的文档完全相同)
// tests/AppBundle/Services/MathTest.php
namespace Tests\AppBundle\Services;
use AppBundle\Services\MathService;
class MathTest extends \PHPUnit_Framework_TestCase
{
protected $math;
public function __construct() {
$this->math = new MathService();
}
public function testSubtract() …Run Code Online (Sandbox Code Playgroud) 我试图在变量目录中存储文件列表(仅使用CLI,Red版本:0.6.3).
我测试了"Red by example"文档中的几个函数,但是它们都只给我一个CLI输出,其中包含目录中的元素列表:
当我尝试将其保存到变量中时,我遇到了如下错误:
>> var: list-dir %tests
other-tests.red README.md poc-tests.red
*** Script Error: var: needs a value
*** Where: var
*** Stack:
>> files: ls tests
other-tests.red README.md poc-tests.red
*** Script Error: files: needs a value
*** Where: files
*** Stack:
>> other: dir %tests
other-tests.red README.md poc-tests.red
*** Script Error: other: needs a value
*** Where: other
*** Stack:
Run Code Online (Sandbox Code Playgroud)
我还找到了调用方法,它使我可以运行外部脚本(如shell脚本),并且我可以执行操作系统命令ls:
>> filelist: ""
>> call/output "ls …Run Code Online (Sandbox Code Playgroud)