函数的PHP单元测试使用$ this关键字调用另一个函数

时间:2017-06-21 11:52:00

标签: phpunit

在PHP中我有这样的函数,它使用searchDateOperator()关键字在同一个类中调用另一个函数$this。如何为此编写单元测试?

public static function segmetDateRangeFilter($searchField, $startDate, $endDate, $dateRange)
{
    $filter = [];

    if ($startDate && !$endDate) {
        $filter = [
            'range' => [
                $this->searchDateOperator($searchField) => [
                    'gte' => strtotime($startDate),
                ]
            ]
        ];
    }

    if ($endDate && !$startDate) {
        $filter = [
            'range' => [
                $this->searchDateOperator($searchField) => [
                    'lte' => strtotime($endDate)
                ]
            ]
        ];
    }

    if ($startDate && $endDate) {
        $filter = [
            'range' => [
                $this->searchDateOperator($searchField) => [
                    'gte' => strtotime($startDate),
                    'lte' => strtotime($endDate)
                ]
            ]
        ];
    }

    if ($dateRange !== '') {

        // $endTime upto current Time
        $endTime = Carbon::now()->timestamp;
        // Start Time . substract the date range days. and in timestamp
        $startTime = Carbon::now()->subDays($dateRange)->timestamp;

        $filter = [
            'range' => [
                $this->searchDateOperator($searchField) => [
                    'gte' => $startTime,
                    'lte' => $endTime
                ]
            ]
        ];
    }

    if ($filter) {
        return $filter;
    }
}

1 个答案:

答案 0 :(得分:0)

您的问题是该方法已声明为静态,但您使用的是$this。如果您调用的方法也是静态的,则应使用self或static,如下所示:

$filter = [
    'range' => [
        self::searchDateOperator($searchField) => [
            'gte' => $startTime,
            'lte' => $endTime
        ]
    ]
];

或者你可以从segmetDateRangeFilter中删除静态并在这样的测试中使用它:

public function testSomething()
{
    $filterFactory = new DateFilterFactory();
    // ...

    $result = $filterFactory->segmetDateRangeFilter(...);

    // Assertions against result
}

您必须使用您使用的任何内容替换班级名称DateFilterFactory