【问题标题】:How to test laravel pipeline如何测试 laravel 管道
【发布时间】:2022-01-22 16:53:33
【问题描述】:

我正在使用管道来过滤消息。

$value = app(Pipeline::class)
        ->send($value)
        ->through([
            HtmlAttributeFilter::class,
            ProfanityFilter::class,
            RemoveTags::class,
        ])
        ->thenReturn();

我想测试这段代码

<?php

namespace App\Filters;

use Closure;

class HtmlAttributeFilter implements FilterInterface
{
    /**
     * Handles attribute filtering removes unwanted attributes
     * @param $text
     * @param Closure $next
     * @return mixed
     */
    public function handle($text, Closure $next)
    {
        $text = str_replace('javascript:', '', $text);
        $text = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/si", '<$1$2>', $text);
        return $next($text);
    }
}

我通过定义自定义闭包来测试这段代码,但我不确定我是否以正确的方式进行操作。我想模拟,但我不知道如何模拟这个对象。以前有人测试过管道吗?任何帮助都将受到高度评价。

我就是这样测试的

$callable = function (string $text) {
        return $text;
    };
    $text = "<html lang='tr'><link href='https://www.example.com'></html>";
    $expectedText = "<html><link></html>";
    $obj = new HtmlAttributeFilter();
    $filteredText = $obj->handle($text, $callable);
    $this->assertEquals($expectedText, $filteredText);

【问题讨论】:

    标签: laravel unit-testing testing


    【解决方案1】:

    我认为给它一个自定义闭包是正确的做法,例如喜欢:

    public function testHtmlAttributeFilterDoesSomething() {
       $next = function ($result) {
            $this->assertEquals('expected value', $result);
            
       };
       app()->make(HtmlAttributeFilter::class)->handle('given value', $next);
    } 
    

    我认为你不需要测试整个管道,只要每个组成部分都经过测试,因为 Laravel 包含测试管道逻辑是否按预期工作的测试

    【讨论】:

    • 谢谢它更干净了
    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 2021-03-01
    • 2017-01-10
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2018-12-12
    相关资源
    最近更新 更多