31 May 2011

How to Mole a Specific Type Instance

So, you're using Moles for unit test dependency isolation.  You have a method to test that (unavoidably) uses several instances of the same type.  You determine a unit test must be created to test that each instance must be tested individually.  Moles is perfect for detouring calls to the API or .NET Framework dependency, but how do you mole a single instance of the common type, instead of all instances of the type?

Moles requires tests to be IN an instrumented process

After adopting Moles as my dependency isolation utility of choice for .NET projects, I began to encounter an exception that could not be explained by anyone, including Peli:
Moles requires tests to be IN an instrumented process.

To compound my frustration, my unit tests involving "moled" types began to work sometimes, and would work other times.  To add frustration, no code changes took place between the successful and unsuccessful test executions.

But something had indeed changed.  Not in the code.  Not on my workstation. Not in Visual Studio 2010 or Team Foundation Server.  How I executed the text changed.

25 May 2011

How to Stub Dependency Event Handlers in Integration Tests

Integration tests help you ensure dependencies behave as expected.  When creating unit tests, developers go to great lengths to eliminate dependencies, but that's not our objective.  The application should already have passed unit tests, before proceeding with integration tests. We want to ensure that integrating the application with its dependencies works as expected.

"Dependencies" includes other modules, APIs, frameworks, hardware, databases, networks, etc.  We want to ensure the application works with these other resources as expected.  This demonstration code implements constructor injection, to simplify testing.  Dependency injection is essential to unit testing, but also proves useful for integration testing.  The injection is important, because we want to isolate a specific dependency and inject a controlled mock object for others.