Testing and Debugging MEF, Tips – Part 1
this is the first post of a series that will offer some tips
about testing and debugging your MEF-able component and application.
in this post we will focus about exporting Mock objects.
if you are not familiar with Mocks you better read more about this subject before
proceeding with this post (in short Mocks are fake object which is use for separate
dependencies during unit testing).
the sample is using the Moq library as it mocking infrastructure.
Having the following code:
2.exported contract implementation
line1: export the class as ILogger
3. contract consumer
line 3: import any available loggers
4. composition and execution
How can we write unit test for the DoYourThings method?
MEF dependencies is already loosely coupled by it nature, but in order to
validate the method behavior we still need to check whether the the method
do write logs.
we will inject a Mock<ILogger> into the MEF container in order to validate
the following code snippet is showing how:
line 7: creating mock object.
line 8: inject the mock object into the container.
using the ComposeExportedValue method, we can inject
mock object into our CompositionContainer, therefore at the composition stage
the Import properties will get our mock objects.