M
M
miy2015-03-05 17:25:01
Yii
miy, 2015-03-05 17:25:01

Unit tests in Yii2. How to mock Active Record static methods?

For example, I have a model.

class MyModel extends Model 
{
    public function foobar() 
    {
            $customer = Customer::find()->where('age>30')->all();
            // bussiness logic
            // .................. 
    }
}

I want to write a unit test for foobar method. My foobar method depends on the static find method of the Customer class. My unit test should not hit the base. Is there any way to mock this Customer::find() method? If possible, show an example.
I'm still leaning towards this solution to the problem that I spied here - https://sebastian-bergmann.de/archives/882-Testing...
class MyModel extends Model 
{
    public function doSomething(Customer $customer = NULL)
    {
        if ($customer === NULL) {
            $customer = Customer::find()->where('age>30')->all();
        }
 
        // ...
    }
}

Maybe there are other options?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Makarov, 2015-03-31
@SamDark

Try to pull the business logic into a separate class that works with the interface and takes what you need from it. In MyModel, implement this interface.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question