【问题标题】:How to test the order of parameters passed to an object constructed by a method如何测试传递给由方法构造的对象的参数顺序
【发布时间】:2017-01-31 01:47:35
【问题描述】:

我正在使用一个返回 TagModel 的方法测试一个简单的工厂类。

class TagFactory
{
    public function buildFromArray(array $tagData)
    {
        return new TagModel(
            $tagData['t_id'],
            $tagData['t_promotion_id'],
            $tagData['t_type_id'],
            $tagData['t_value']
        );
    }
}

我可以测试这个方法……

public function testbuildFromArray()
{
    $tagData = [
        't_id' => 1,
        't_promotion_id' => 2,
        't_type_id' => 3,
        't_value' => 'You are valued',
    ];    

    $tagFactory = new TagFactory();
    $result = $tagFactory->buildFromArray($tagData);
    $this->assertInstanceOf(TagModel::class, $result);
}

如果我更改new TagModel… 中的参数顺序,测试仍然会通过。

如果我预言TagModel...

$tagModel = $this->prophesize(TagModel::class);
    $tagModel->willBeConstructedWith(
        [
            $tagData['t_id'],
            $tagData['t_promotion_id'],
            $tagData['t_type_id'],
            $tagData['t_value']
        ]
    );

...但是我应该断言什么呢? assertSame 不起作用,因为它们不是。

我可以使用来自TagModel 的 getter 来测试订单,但是我已经超越了仅测试这个单元。但我确实觉得应该测试订单,因为如果我更改它们,测试仍然通过。

【问题讨论】:

    标签: php phpunit prophecy


    【解决方案1】:

    您正在测试的方法是工厂。它创建一个对象。如果确保它是预期的类型对您来说还不够,您需要验证它的状态。要么用 getter 检查它,要么创建一个你期望接收的对象并使用 assertEquals() 来比较它。

    【讨论】:

    • 谢谢,我已经完成了,这意味着这个测试本质上变成了一个 TagModel 测试以及测试参数是否以正确的顺序传递。
    猜你喜欢
    • 1970-01-01
    • 2014-07-15
    • 2021-09-25
    • 2012-07-09
    • 2011-11-28
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多