4

Given that I am using EcomDev's PHPUnit framework to write unit tests for my Magento modules, sometimes I come across a controller action that has too much logic within it. It would mean mocking lots of objects and probably providing lots of fixtures to create an effective unit test for methods like this.

Of course, in hindsight the methods should have been written to be smaller and utilize models and helpers wherever possible in small, testable functions, but retrofitting unit tests doesn't really give you that flexibility.

My question is: when situations like this occur, should I:

  1. Refactor the original controller method to be more modular and easy to unit test
  2. Battle on through what looks to be an inefficient method to write unit tests for (time to write test greatly outweighs the benefit of having it)
  3. Skip writing unit tests for this method altogether
3

Please do not skip writing unit tests. Especially for these more complex problems unit tests are very important.

So I would suggest to refactor the controller in a test driven development way. Which means yes for now create your unit tests by mocking all these objects. To be precise that probably won't be real unit tests, as they might test a lot more than just a unit. ;)

As soon as you have these tests you can start to refactor your method, as you can now run your tests every time and be safe that you didn't break anything. In this process you can also refactor your tests by basically adding more, but a lot smaller tests, which really test only a small unit of your code and don't have a lot of dependencies which you have to mock.

Finally you'll get a much more maintainable code base, for the business logic as well as for the unit tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.