Laravel测试自定义刀片是否

时间:2018-06-23 15:55:15

标签: php laravel laravel-5

如果要在laravel中尝试对自定义刀片进行单元测试。

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Filesystem\Filesystem;
use Illuminate\View\Compilers\BladeCompiler;

class BladeIfAdminStatementTest extends TestCase
{
    public function testIfAdminStatementAreCompiled()
    {
        $compiler = new BladeCompiler(\Mockery::mock(Filesystem::class), __DIR__);

        $string = '@admin test @endadmin';
        $expected = '<?php if(auth->check() && auth()->user()->isAdmin()): ?> test <?php endif; ?>';

        $this->assertEquals($expected, $compiler->compileString($string));
    }
}

在AppServiceProvider.php

<?php


...

public function boot()
{
    \Blade::if('admin', function () {
        return auth()->check() && auth()->user()->isAdmin();
    });
}

当我运行phpunit时,我得到了:

Failed asserting that two strings are equal.
Expected :'<?php if(auth->check() && auth()->user()->isAdmin()): ?> test <?php endif; ?>'
Actual   :'@admin  test @endadmin'

当我尝试将$string@admin test @endadmin更改为@if(true) test @endif并运行phpunit时:

Failed asserting that two strings are equal.
Expected :'<?php if(auth->check() && auth()->user()->isAdmin()): ?> test <?php endif; ?>'
Actual   :'<?php if(true): ?> test <?php endif; ?>'

请注意,它失败了,但是@if语句正确编译了,而我的自定义@admin语句却没有正确编译。

2 个答案:

答案 0 :(得分:1)

只需像这样访问compileString方法:

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Support\Facades\Blade;


class BladeIfAdminStatementTest extends TestCase
{
    public function testIfAdminStatementAreCompiled()
    {

        $bladeSnippet = '@admin test @endadmin';
        $expectedCode = '<?php if(auth->check() && auth()->user()->isAdmin()): ?> test <?php endif; ?>';

        $this->assertEquals($expectedCode, Blade::compileString($bladeSnippet));
    }
}

答案 1 :(得分:0)

compileString将编译字符串并为您返回代码结果。

每个刀片语句将被评估然后返回。

您是否尝试断言结果而不是php代码?