简体   繁体   English

如何在 phpunit 测试中期待 diff() 方法?

[英]How to expects diff() method in phpunit test?

I'm a phpunit test beginner.我是 phpunit 测试初学者。 I have a class like this:我有一个像这样的 class :

class ClassA
{
    public function tracking($date)
    {
        //... something

        $now = new \DateTime();
        $days = $date->diff($now, false)->days;
        $hours = $date->diff($now, false)->h;
        $minutes = $date->diff($now, false)->i;

        //... something
        return true;
    }
}

Then, I want to unit test tracking() method.然后,我想对tracking()方法进行单元测试。 So I make a test like this:所以我做了一个这样的测试:

class ClassATest extends TestCase
{
    /**
     * @dataProvider trackingDataProvider()
     * @param $params
     * @param $expected
     */
    public function testTracking($params, $expected)
    {
        $classA = new ClassA();
        $result = $classA->tracking($params['data']);
        $this->assertEquals($expected, $result);
    }

    public function trackingDataProvider()
    {
        return [
            'happy-case-1' => [
                'params' => [
                    'data' => new \DateTime()
                ],
                'expected' => true
            ],
        ];
    }
}

I run test and there is error: Error: Call to a member function diff() on array .我运行测试并且出现错误: Error: Call to a member function diff() on array How can I suppose diff() will return specified value to test?我怎么能假设 diff() 将返回指定的值进行测试? Please help!请帮忙!

You are trying to compare a DateTime object with $expected .您正在尝试将DateTime object 与$expected进行比较。 I do not know what this variable really holds, since there is not type hinting.我不知道这个变量到底是什么,因为没有类型提示。 If it is a DateTime object, then you will need to get the correct format and type from it.如果它是 DateTime object,那么您需要从中获取正确的格式和类型。

// Get as formatted string
(new \DateTime)->format('Y-m-d');

OR或者

// Get as timestamp integer
(new \DateTime)->getTimestamp();

The same must also be done with $result . $result也必须这样做。 So just as an explanatory example you should have below values at the end to check them for equality.因此,作为一个解释性示例,您应该在最后使用以下值来检查它们是否相等。

// as format
$expected = '2020-04-16';
$result = '2020-04-16';

// as timestamp
$expected = 1587033720;
$result = 1587033720;

Also if your function tracking returns a boolean, then you must do following.此外,如果您的 function tracking返回 boolean,那么您必须执行以下操作。
Either assertTrue();要么assertTrue(); or assertEquals(true, $result)assertEquals(true, $result)

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

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