TDD in yii2

I’m new to Yii2, have been developing in Yii1 for about a year. As far as I can see unit testing is very limited in this version. What got me to this conclusion is that almost all ActiveRecord functions are static: (findAll, find…). I know that it’s possible to mock static functions but the problem I encountered was I could not mock their return values on consecutive calls( 2 findAll() calls on the same class in one function ). Am I missing something or the only way to test complex logic is go the fixture path. I wouldn’t be writing this if using fixtures was fine for me but I feel that relying strongily on the data is not right, maybe it’s becouse I’ve been listening to Uncle Bob too much.

Codeception ??

Yii has strong support for Codeception so you need to check it out:

Both Basic and Advanced project templates has testing fully functional out of the box.

The only thing you need to do - if you want to run ‘codecept’ globally - is to install the codeception tool globally.

You can call methods on the models in unit tests just fine - or do I misunderstand your issue?

I know that the docs are a bit scarce…

But take a look at yii2-user - they have great testing code:

Look in unit/userTest and see for yourself :)

I’ve seen docs for Codeception and they did not help.

I was talking about situation where you have to call findAll in one function multiple times. Each time has to return different value. I understand that it’s imposible to mock those calls becouse of static functions nature.

What bothers me is that ActiveRecord functions are static. I know that you can mock those with AspectMock but in Yii1 with proper dependecy injection you could test your code in more flexible way becouse CActiveRecord functions were not static.

Ofcourse one can say that I want to mock too much stuff and this way I end up with tests tightly coupled to implementation which is not a good thing either.

What about fixtures? I would want to use fixtures for functional testing only rather than unit testing becouse they are very time costly and you do not fully control what’s happening.

In the end I redesigned my code so I don’t have to mock consecutive calls on static functions.

I ran into some similar confusion when I was first trying to update my testing for Yii 2.

Perhaps some of this information will help?

Probably the reason why Yii 2 is much faster and leaner than Yii 1 :)

Awesome blog post Dana ! :D

Thank you!