Third Party Components with TDD
Am trying to get started using TDD on a class which spits out an object belonging to a third party component. However am getting a bit confused in that apparently:
a) With unit tests objects should be tested in isolation
b) Third-party components should be wrapped into an adapter
Do these rules apply when writing tests for code which returns an instance of an object belonging to a third party component? As an example, here's the test so far:
// Arrange
string foodXml = "<food><ingredient>Cabbages</ingredient>" +
"<ingredient>Bananas</ingredient></food>";
IFoodMixer mixer = new FoodMixer();
// Act
// Smoothie is the third-party component object
Smoothie urgh = mixer.Mix(foodXml);
// Assert
Assert.AreEquals("Cabbages", urgh.Ingredients[0].Name);
Assert.AreEquals("Bananas", urgh.Ingredients[1].Name);
Apologies if this question seems a bit basic (or if the concept above seems a tad silly!) - am just struggling to understand how the two rules above could apply in thi开发者_C百科s situation.
Thanks in advance for any advice given!
I would be practical with it. If Smoothie is just a data object, don't bother wrapping it.
There's something inside that FoodMixer which is creating the Smoothie in the first place. If that's a 3rd party component, I would wrap it up (you can delegate from a class to a static method if required), then dependency-inject the wrapper and mock it out in your unit test.
Your unit test is then describing the behaviour and responsibilities of your FoodMixer, independently of the SmoothieMaker (whether it's 3rd-party or otherwise). Part of the FoodMixer's responsibility is to ask the SmoothieMaker for a Smoothie, not to actually make the Smoothie itself. By mocking it out we can express that responsibility and class scope.
If your Smoothie is not just a data object but has rich behaviour, I would wrap that within your wrapped SmoothieMaker too.
Now you are completely decoupled from your 3rd party libraries, and you can unit-test easily as a useful by-product.
Look at mockito as a simpler way to create mocks automatically and verify assertions instead of using adapters. There are also many good tutorial on mockito (and JMocks) that are also good TDD tutorials.
精彩评论