C# – How would you TDD the functionality of getting the corresponding process of a running windows service

cdesigntddunit testingvb.net

Purpose

Over the last year or more I've been learning unit testing via books I've read recently like The Art of Unit Testing, Working Effectively with Legacy Code, and others. I've also been using unit tests, mocking frameworks, and the like, periodically at work and definitely see the value.

However, I'm still having a hard time wrapping my mind around TDD (as opposed to TAD) when the situation calls for code that is gong to mostly use external API calls.

Problem to solve

Get the process associated with a windows service using the service name.

example: Function GetProcess(ByVal serviceName As String) As Process

Rules

  • Show each major iteration in production & test code using TDD
    • No need to see any other code or configuration that is required to get things to run. Just curious about the interfaces, concrete classes, and test methods.
  • C# or VB.NET
  • Must use the .Net framework regarding services/processes (i.e. System.Diagnostics.Process)
  • Test Frameworks:
    • Nunit or MSTest
  • Isolation Frameworks:
    • Moq, Rhino Mock, or Microsoft Moles
  • Must write true unit tests (no integration tests)

Additional notes

As far as I can tell there are two approaches design wise.

  1. Use an Inversion of Control approach along with using the Adapter and/or Facade patterns to wrap the underlying .net framework objects dealing with processes and services.
  2. Keep the .net framework code in the class containing the Get Process method and use code detouring (interception) via Microsoft Moles to isolate the hard dependencies from the method under test.

Best Answer

I am not sure I understand why do you want to do this (apart from dealing with an intellectual challenge). This kind of code, where you work directly with some system level API, is very hard to unit test, TDD style or not, and to be frank, I don't find it very valuable to try it in a real project.

Most of the task you describe is calling the right low level API method with the right parameter. And the rest of the code as is may be so trivial, it wouldn't necessarily warrant the introduction of a dedicated interface, mock objects etc. I would be content having an integration test to verify on a higher level that the whole stuff works. But this is just my 2 cents.

Unit testing for me is not about following rulebooks or strict definitions. In real life, I don't really care whether my tests are "real" unit tests or not; as long as my code is being covered by automated and repeatable tests, I am fine. I prefer the pragmatic approach.

Related Topic