Home > Enterprise >  Make a Stub for nesting function in Yii2
Make a Stub for nesting function in Yii2

Time:12-10

I learn to use Unit test in Yii2 with Codeception, and try to check if a billing is a "daily" billing from a merchant's setting.

$this->biller->merchant->detail->rule_type == self::PERIODIC_MODE_DAILY

I don't know how to mock that rule_type value if I use a Stub::make() function.

What I tried so far is using the nested array like this (doesn't work) :

$billing = Stub::make(Billing::class, [
    'status'        => Billing::STATUS_ACTIVE,
    'set_periodic_by' => Billing::SET_PERIODIC_BY_MERCHANT,
    'biller' => [
        'merchant' => [
            'detail' => [
                'rule_type' => Billing::PERIODIC_MODE_DAILY,
            ]
        ]
    ]
]);

And I also tried to mock each of the object model using another Stub::make()

$billing = Stub::make(Billing::class, [
    'status'        => Billing::STATUS_ACTIVE,
    'set_periodic_by' => Billing::SET_PERIODIC_BY_MERCHANT,
    'getBiller' => Stub::make(Biller::class, [
        'getMerchant' => Stub::make(Merchant::class, [
            'getDetail' => Stub::make(MerchantDetail::class, [
                'rule_type' => Billing::PERIODIC_MODE_DAILY,
            ])
        ])
    ])
]);

How do I properly create a "nested" function return values using Stub? Any comment or answer is always welcome.

CodePudding user response:

Casting the nested array to (object) will do

$billing = Stub::make(Billing::class, [
    'status'                => Billing::STATUS_ACTIVE,
    'set_periodic_by'       => Billing::SET_PERIODIC_BY_MERCHANT,
    'getBiller'             => (object) [
        'merchant'          => (object) [
            'detail'        => (object) [
                'rule_type' => Billing::PERIODIC_MODE_DAILY,
            ]
        ]
    ]
]);
  • Related