czwartek, 13 sierpnia 2015

Testing MVC Controllers

Couple days ago I started learning MVC. Wonderful how knowledge is available all over internet. Indeed, being master of pen is quite a trick so lets get down to the business. After discovering how MVC is supposed to work and playing around, came the time to get little bit more serious. Unit testing. So what approach default HomeControllerTest was suggesting:
Quite fair. Testing Controllers looks really simple! At first I went for Moq to test my basic operations Create, Update, Delete, GetAll and Find. It went pretty nice, but 300-500ms per test just to make sure that proper method on the repository is called and operate on List<> was a huge waste of time. That's how RepositoryStub got born.
Now that's better, implementing that for concrete class is even easier and needed just to make Find method working as the Controller was using it. I could probably just return any element from _items, but it wasn't much more of an effort and provided me with some more flexibility when testing. Here's implementation for EmployesRepositoryStub
After replacing Moq's fake repository with mine, results were much more satisfying.

But wait! Where are those tests? Well that's another story. My first attempt to cover all the methods (except for dispose, I'll take care of it later) took almost 150 lines of code and way more time trying to exctract some abstraction from it (back the time when it was still Moq). With my brand new, generic RepositoryStub I went for beautiful journey to the far lands, where the abstractions get born from chaos (big thanks to Uncle Bob). Here's ControllerTest
Only thing about that I don't like is how I initialize all the fields in base class, but maybe there'll be some time for that other day. With this test I'll be sure to cover 77.03% of my EmployeeController that is everything except for two other constructors, override dispose method and six more lines that will be tested after I create validation for Employee model. Finally horror of writing all that from scratch or even worse, duplicating such wast amounts of code, everytime I want to have new simple controller, moves out of my sight. Currently I need 11 lines to create new repository stub and exactly 16 for each test, which is at least 100 less to write :]

Brak komentarzy:

Prześlij komentarz