In my unit tests, especially tests that are very data driven like DAO's and validators I found myself doing this alot:
As the screencap shows, there are many time where you need to setup data sets that will be used during assertions or mocks and usually start out inline. You'll find yourself duplicating tests that really assert the same thing just with a different data set. I admit that in unit tests I've become lazy and often times do not even create a private method that returns a pseudo dataset for reuse, yea yea I'm sorry. I just duplicate this code above in each method that needs it because it feels innocuous in a test, I mean after all its simply a query with one record for goodness sake. Well with the new MXUnit data providers its time for me to stop whining because they've made it extremely easy to declare a dataset (DataProvider) and have it injected into the test by doing just three things so:
- Create your dataprovider in the setup() as a class level member (variables scope)
- Annotating your function using the @mxunit:dataprovider annotation with the value being the dataprovider you want to inject.
- Referencing that dataset as an argument in your test method
Here's how it looks like now (with the provider flow):
Booya - that DataProvider is now available to any test method in that TestCase. No need to write duplicate code or private methods. MXUnit simply passes it off politely to your test method. If you have multiple rows in the query it iterates each and fires your unit test, no more separate tests essentially doing the same thing. Damn you MXUnit for making me write better, more efficient code.
MXUnit all the way.