Concrete Example – Mocking .NET Objects w/NUnit

Geoff Lane does a very good job of explaining .NET Mock objects.

People were requesting a “concrete” example so I implemented an example C# console application (although this can easily be made into an ASP.NET web application).

Geoff hints to using Spring .NET to wire things up, but that might be too confusing for some people. And maybe a little over board for a simple example (open closed principle).

So instead I created a PersonServiceManager that creates a “concrete” PersonService via IPersonRepository injection. The GUI communicates to the PersonServiceManager through an IPersonService interface.

Instead of “mocking” an IPersonRepository, we are actually implementing it then injecting it into PersonService (just like our NUnit test). The PersonServiceManager handles passing the appropriate database connection string down to the data layer. In my example, the data layer object PersonDb (which implements IPersonRepository and used for injection) utilizes the DbProviderFactory.

Here is the sample source (C# Console App).

Also remember that the sample source could be broken down into separate assemblies in a real world project.

Advertisements
This entry was posted in .net, testing. Bookmark the permalink.

3 Responses to Concrete Example – Mocking .NET Objects w/NUnit

  1. Anonymous says:

    I want to quote your post in my blog. It can?And you et an account on Twitter?

  2. Anonymous says:

    thanks for doing this!i understand the benefit of using an interface for the repository as we can create alternate implementations or mock versions for the testing, but what other implementations of personservice might there be?would this primarily be so we could create a mock? what would we be testing in that case?if we wanted to test the presentation layer somehow, couldn't we use the concrete personservice alongside a mock repository?

  3. Kim Olsen says:

    This sounds interesting..can u reup the sample code? thx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s