zendframework/zf2-documentation — pull request #356 by mmoussa (2012-10-03 14:15:08+00:00)
Title: Added unit tests and instructions for AlbumTable

This Pull Request warrants more explanation/justification than my previous unit test ones.

While writing tests for the AlbumTable class, I found it extremely difficult due to AlbumTable extending AbstractTableGateway. There wasn't any way to mock out the select/delete/etc calls directly. The best I could do was mock out the DbAdapter, but doing so would require analyzing and mocking out a whole lot of the guts of the AbstractTableGateway's behavior (which would likely break immediately if the internals of AbstractTableGateway ever changed - even if the API were left alone).

After consulting the [ZF2 docs](http://packages.zendframework.com/docs/latest/manual/en/modules/zend.db.table-gateway.html), I decided it would make a lot more sense for AlbumTable to accept a TableGateway parameter rather than extend AbstractTableGateway.

Why? From the docs...

> The TableGateway concrete implementation simply adds a sensible constructor to the AbstractTableGateway class so that out-of-the-box, TableGateway does not need to be extended in order to be consumed and utilized to its fullest."

The original implementation of AlbumTable doesn't add any gateway-specific functionality (so, arguably, it violates SRP). Even if it did, that special logic could be implemented using the Features API. Also from the docs:

> In addition, AbstractTableGateway also implements a 'Feature' API, that allows for expanding the behaviors of the base TableGateway implementation without having to extend the class with this new functionality."

After making the change (and modifying the Service Manager logic to know how to instantiate using this new setup), I was able to easily write the AlbumTable tests by just mocking out the TableGateway and setting some expectations on select/delete/update/insert.

I hope you'll find that this makes sense and is a better design. I've tested it (by hand, since a full test suite is not done yet) with the zf2-tutorial project and it works fine. I'll be sending a Pull Request there as well.