Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Unit Testing and Mock Objects

Last night I read chapter 6 of Pragmatic Unit Testing - In C# with NUnit which covered using mock objects. I found the idea of mock objects interesting but, despite the examples given in the book, had a hard time trying to think of some good cases for using mock objects. Sure, the network could become unavailable, hard drives can fail, memory failures can happen, etc. I'm curious what other NUnit and perhaps DotNetMock users have found to be useful cases for employing mock objects in their unit tests. Anyone care to share their experiences?

4 Comments

  • Mocks aren't just for imitating 'expensive' resources like databases or file-systems. They allow you to test the actual interactions an object has with other objects (as opposed to state-based testing, which just checks the result of those interactions). Additionally, unit tests become more targeted, as you tend to focus on the behaviour of one class at a time rather than a 'cluster' of related classes. I would recommend www.mockobjects.com or nmock.org for some examples.



    Jim

  • October's MSDN Magazine has an article discussing mock objects.

  • mockobjects are there to fully utilize TDD: you test your design with mock objects before you implement it, which is the best way to approach it.



    After the unit tests with the mock objects work, you know your design is ok, and you can replace the mock objects one by one with your real code, always falling back on the unit tests to see if you're doing your job properly. After all the mock objects are replaced with your real code and your tests still work, you're done. :)



  • You also have to consider scenarios like asp.net server controls. Inside of a unit test you won't have a HttpContext. With mock objects you can fake these elements and still test a control.



Comments have been disabled for this content.