Archive for the ‘Mock’ Category.

Better Unit Tests in C#

When you test the right thing, you get better unit tests. Better unit tests often lead to better design, testable design, and easier maintainability of code.

Look at an example of testing a Copy() method in a Person object. You will see that as you unit test this method, you are forced to think. If you think about what you really want to test (instead of just thinking about 100% coverage), and test for that, it will lead you to changing your code for the better.

With a Copy() method, you want to make sure that every property in the Person object is copied. You want to make sure that any new Property added in the future is copied.

Lets see if we can do this. Lets start with our simple example Person object with a Copy() method and lets test the copy method.

using System;

namespace FriendDatabase
{
    public class Person
    {
        #region Properties
        public int Age { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        #endregion

        #region Methods
        public Person Copy()
        {
            Person retPerson = new Person();
            retPerson.Age = this.Age;
            retPerson.FirstName = this.FirstName;
            retPerson.LastName = this.LastName;
            return retPerson;
        }
        #endregion
    }
}

Lets list the three most obvious tests for the copy method.

  1. Age is the same value.
  2. FirstName is the same value.
  3. LastName is the same value.

If you are an expert at Unit Testing, you are probably already thinking that there are more tests to run that just these three tests.0

A simple Unit Test

A test for this that would give use 100% code coverage and covers the three most obvious tests would be as follows:

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 0 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    Assert.AreEqual(p.Age, copy.Age);
    Assert.AreEqual(p.FirstName, copy.FirstName);
    Assert.AreEqual(p.LastName, copy.LastName);
}

The code coverage is now 100%. But is this a good test? No.

What are the problems with our tests?

Problem 1 – The Unit Test does not guarantee every property is copied

In the Person.Copy() method, comment out the line that copies the Age. Run the test again.

Oops! The test still passes.

What is the problem? Well, int defaults to zero.

Change the age to a value other than zero and try again.  The test now fails.

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 25 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    Assert.AreEqual(p.Age, copy.Age);
    Assert.AreEqual(p.FirstName, copy.FirstName);
    Assert.AreEqual(p.LastName, copy.LastName);
}

This fixed this one problem.

Is the test good enough now? Of course not.

Problem 2 – The Unit Test does not guarantee every property is copied

Wait, you might be saying that my problem 2 is named the same as problem 1 and you might think this is a typo. It is not a typo.

We still have a similar problem to the first problem.

Imagine a new user developer takes over the code, and decides that a MiddleName property is needed. Go ahead and add a middle name property. Don’t modify the Copy() method yet. Now run your Unit Test again.

Our one test still passes.

Shouldn’t there be a test that fails because the copy is now failing to copy to all properties? Yes there should. We have just identified a new test that actually includes the previous three tests. The goal of our three tests were all the same overall goal. Our three tests were actually slightly wrong. Instead we really had only one test: Test that when Copy() is invoked, all properties should be copied.

Now that we have gain more insight on what we are actually testing, how do we test it? How do we test all properties. One idea might be to use reflection.

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 25 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    PropertyInfo[] propInfo = typeof(Person).GetProperties();
    foreach (var prop in propInfo)
    {
        object pObj = typeof(Person).GetProperty(prop.Name).GetValue(p, null);
        object copyObj = typeof(Person).GetProperty(prop.Name).GetValue(copy, null);
        Assert.AreEqual(pObj, copyObj);
    }
}

At first this looked like a good idea, because it will check each property for us, even properties added in the future. However, it turns out that because int and string have default values, This test didn’t exactly test what we wanted to test. This test still passes when it should fail and that is a problem.

Remember the test: to test that when Copy() is invoked, all properties should be copied.

We need guarantee that each property was called and to do this. If only we were using an interface, then we could mock the interface and assert that each public property were called…A good rule to live by when developing is if you hear yourself say or you think “if only…” you should actually try implementing the “if only…” you just thought of. So lets do that.

This is a little longer of a solution but a better design, so here are some steps to get there.

  1. Create an IPerson interface that has the properties and methods we want to guarantee exist.
    using System;
    
    namespace FriendDatabase
    {
        public interface IPerson
        {
            int Age { get; set; }
            String FirstName { get; set; }
            String MiddleName { get; set; }
            String LastName { get; set; }
    
            IPerson Copy();
            void CopyTo(IPerson inIPerson);
        }
    }
    
  2. Change the person object so that you can never get a Person object, you always get an IPerson.
  3. We also need to be able to mock the instance of IPerson that is getting created by the Copy method and our current design doesn’t allow for that. Lets change our Copy method and add a CopyTo method to make this possible.
    using System;
    
    namespace FriendDatabase
    {
        public class Person : IPerson
        {
            #region Constructor
            ///
    <summary> /// Nobody should use Person, but on GetPerson()
     /// which returns and IPerson
     /// </summary>
            protected Person()
            {
            }
            #endregion
    
            #region Properties
            public int Age { get; set; }
            public String FirstName { get; set; }
            public String MiddleName { get; set; }
            public String LastName { get; set; }
            private String NickName { get; set; }
            #endregion
    
            #region Methods
            public static IPerson GetPerson(string inFirstName, string inMiddleName, String inLastName = null, int inAge = 0)
            {
                return new Person()
                {
                    FirstName = inFirstName,
                    MiddleName = inMiddleName,
                    LastName = inLastName,
                    Age = inAge
                };
            }
    
            public IPerson Copy()
            {
                IPerson retIPerson = new Person();
                CopyTo(retIPerson);
                return retIPerson;
            }
    
            public void CopyTo(IPerson inIPerson)
            {
                inIPerson.Age = this.Age;
                inIPerson.FirstName = this.FirstName;
                inIPerson.LastName = this.LastName;
            }
            #endregion
        }
    }
    
  4. Now we need a Mocking tool. Download you favorite mocking library (RhinoMocks, NMock2, or MOQ). I am going to use NMock2 which can be downloaded here: NMock2
  5. Lets put the mocking library in a lib directory in your test project.
  6. Add a reference to the dll.
  7. Now lets change our test. Lets go ahead and use the reflection still, but this time, we want to guarantee that each property was called.
    [Test]
    public void Person_Copy_All_Properties_Copied_Test()
    {
        // Step 1 - Arrange
        Mockery mock = new Mockery();
        IPerson p = Person.GetPerson("John", "J.", "Johnson", 25);
        IPerson mockIPerson = mock.NewMock();
        PropertyInfo[] propInfo = typeof(IPerson).GetProperties();
    
        // Step 2 - Expect
        foreach (var prop in propInfo)
        {
            Expect.AtLeastOnce.On(mockIPerson).SetProperty(prop.Name);
        }
    
        // Step 3 - Act
        p.CopyTo(mockIPerson);
    
        // Step 4 - Assert
        mock.VerifyAllExpectationsHaveBeenMet();
    }
    

    Note: NMock2 requires a slight variation of the Arrange, Act, Assert (AAA) unit test model in that it is more Arrange, Expect, Act, Assert (AEAA), which is just as good and just as clean. One could argue that the expectations are part of the Arrange and I would somewhat agree with that too.

  8. Ok, now run your test again and it should fail because we are not calling MiddleName in our CopyTo() method. You have now written the correct unit test for the goal.

So by taking time to think of the correct test and Unit Testing the correct test, solving the right problem, we gained a few benefits.

  • Better future maintainability
  • Better design
  • Testable design

Now hopefully you can go and do this when you write your Unit Tests.

Return to C# Unit Test Tutorial

How to Mock an internal interface with NMock2?

I was attempting to mock an internal interface with NMock2 and no matter what I tried I continued to get the following failure.

Test 'M:ExampleOfIVT.PersonTests.FirstTest' failed: Type is not public, so a proxy cannot be generated. Type: ExampleOfIVT.IPerson
	Castle.DynamicProxy.Generators.GeneratorException: Type is not public, so a proxy cannot be generated. Type: ExampleOfIVT.IPerson
	at Castle.DynamicProxy.DefaultProxyBuilder.AssertValidType(Type target)
	at Castle.DynamicProxy.DefaultProxyBuilder.CreateInterfaceProxyTypeWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
	at NMock2.Monitoring.CastleMockObjectFactory.GetProxyType(CompositeType compositeType)
	at NMock2.Monitoring.CastleMockObjectFactory.CreateMock(Mockery mockery, CompositeType typesToMock, String name, MockStyle mockStyle, Object[] constructorArgs)
	at NMock2.Internal.MockBuilder.Create(Type primaryType, Mockery mockery, IMockObjectFactory mockObjectFactory)
	at NMock2.Mockery.NewMock[TMockedType](IMockDefinition definition)
	at NMock2.Mockery.NewMock[TMockedType](Object[] constructorArgs)
	PersonTests.cs(59,0): at ExampleOfIVT.PersonTests.FirstTest()

Obviously I have a project, ExampleOfIVT, and a test project, ExampleOfIVTTests.

All the Google searching suggested that I should be adding these lines to my AssemblyInfo.cs file in the ExampleOfIVT project but these line did NOT work.

Please not that I downloaded NMock2 from here: http://sourceforge.net/projects/nmock2/

[assembly: InternalsVisibleTo("Mocks")]
[assembly: InternalsVisibleTo("MockObjects")]

Turns out that they have changed to use Castle.DynamicProxy and so the only assembly I needed was this one.

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Return to C# Unit Test Tutorial

Unit Testing Registry access with RhinoMocks and SystemWrapper

As mentioned in the previous Unit Test post (Unit Testing Registry access with RhinoMocks and SystemWrapper) it important to be able to Unit Test code that access the registry without really accessing the registry.

Prerequisites

Step 1 – Download SystemWrapper

You may have already done this when reading the previous post, if not do so now.

  1. Go to https://github.com/jozefizso/SystemWrapper and download the latest dll or the latest source or add the SystemWrapper.Interfaces and SystemWrapper.Wrappers By jozef.izso
  2. Copy the SystemInterface.dll and SystemWrapper.dll into your project (perhaps you already have a libs directory).
  3. Add references to these two dlls in your release code.
  4. Add a reference only to SystemInterface.dll in your Unit Test project.

Step 2 – Change your code to use Interfaces and Wrappers

Ok, so here we are going to start with an example. Here is an object that I wrote myself that uses the registry to check on which versions of .NET Framework are installed. It is currently using Registry and RegistryKey directly.

using System;
using Microsoft.Win32;

namespace SystemInfo
{
    public class DotNetFramework
    {
        #region Constant members
        public const string REGPATH_DOTNET11_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v1.1.4322";
        public const string REGPATH_DOTNET20_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v2.0.50727";
        public const string REGPATH_DOTNET30_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0";
        public const string REGPATH_DOTNET35_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
        public const string REGPATH_DOTNET40_VERSION_CLIENT = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client";
        public const string REGPATH_DOTNET40_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full";
        #endregion

        #region Properties
        /// <summary>
        /// This returns true if .NET 4 Full is installed.
        /// </summary>
        public bool FoundDotNet4
        {
            get { return HasDotNetFramework(REGPATH_DOTNET40_VERSION, 0); }
        }

        /// <summary>
        /// This returns true if .NET 4 Client is installed.
        /// </summary>
        public bool FoundDotNet4Client
        {
            get { return HasDotNetFramework(REGPATH_DOTNET40_VERSION_CLIENT, 0); }
        }

        /// <summary>
        /// This returns true if .NET 3.5 with SP1 is installed.
        /// </summary>
        public bool FoundDotNet35SP1
        {
            get { return HasDotNetFramework(REGPATH_DOTNET35_VERSION, 1); }
        }

        /// <summary>
        /// This returns true if .NET 3.5 is installed.
        /// </summary>
        public bool FoundDotNet35
        {
            get { return HasDotNetFramework(REGPATH_DOTNET35_VERSION, 0); }
        }

        /// <summary>
        /// This returns true if .NET 3.0 with SP2 is installed.
        /// </summary>
        public bool FoundDotNet30SP2
        {
            get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 2); }
        }

        /// <summary>
        /// This returns true if .NET 3.0 with SP1 is installed.
        /// </summary>
        public bool FoundDotNet30SP1
        {
            get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 1); }
        }

        /// <summary>
        /// This returns true if .NET 3.0 is installed.
        /// </summary>
        public bool FoundDotNet30
        {
            get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 0); }
        }

        /// <summary>
        /// This returns true if .NET 2.0 with SP2 is installed.
        /// </summary>
        public bool FoundDotNet20SP2
        {
            get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 2); }
        }

        /// <summary>
        /// This returns true if .NET 2.0 with SP1 is installed.
        /// </summary>
        public bool FoundDotNet20SP1
        {
            get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 1); }
        }

        /// <summary>
        /// This returns true if .NET 2.0 is installed.
        /// </summary>
        public bool FoundDotNet20
        {
            get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 0); }
        }

        /// <summary>
        /// This returns true if .NET 1.1 is installed.
        /// </summary>
        public bool FoundDotNet11
        {
            get { return HasDotNetFramework(REGPATH_DOTNET11_VERSION, 0); }
        }
        #endregion

        public bool HasDotNetFramework(string dotNetRegPath, int expectedServicePack)
        {
            bool retVal = false;

            try
            {
                RegistryKey localKey = Registry.LocalMachine.OpenSubKey(dotNetRegPath);
                if (localKey != null)
                {
                    int? isInstalled = localKey.GetValue("Install") as int?;
                    if (isInstalled != null)
                    {
                        if (isInstalled == 1)
                        {
                            if (expectedServicePack > 0)
                            {
                                if ((int)localKey.GetValue("SP") >= expectedServicePack)
                                    retVal = true;
                            }
                            else
                            {
                                retVal = true;
                            }
                        }
                    }
                }
                return retVal;
            }
            catch
            {
                return retVal;
            }
        }
    }
}
  1. Find any place in your code where you use touch the system. For example, if you touch the registry, find any place you call Registry or RegistryKey objects or reference Microsoft.Win32.
    Hint: Use the search feature in your IDE.
  2. Replace the reference with a reference to SystemWrapper and SystemInterfaces. For example, if replacingrRegistry code,
    SystemInterface.Microsoft.Win32
    SystemWrapper.Microsoft.Win32In the DotNetFramework.cs file above, there is a using statement to Microsoft.Win32. Our new using statements will be:

    using System;
    using SystemInterface.Microsoft.Win32;
    using SystemWrapper.Microsoft.Win32;
    
  3. For any object that touches the system, change that object to be instantiated using the interface. For example, replace RegistryKey objects with IRegistryKey objects.In the DotNetFramework.cs file, there is only one single line that needs to change to do this, line 113.
    This line…

        RegistryKey localKey = Registry.LocalMachine.OpenSubKey(dotNetRegPath);
    

    …changes to this line.

        IRegistryKey localKey = new RegistryWrap().LocalMachine.OpenSubKey(dotNetRegPath);
    

Step 3 – Allow for replacing the IRegistryKey objects

Create a property or function that allows you to replace the object you are mocking so you can pass in an object that is mocked.

This is done for you to some extent for registry access by using the IAccessTheRegistry interface.

  1. Implementing the IAccessTheRegistry interface from the SystemInterface.Microsoft.Win32 namespace. You can add the following code to the DotNetFramework object.
            #region IAccessTheRegistry Members
    
            public IRegistryKey BaseKey
            {
                get
                {
                    if (null == _BaseKey)
                        _BaseKey = new RegistryWrap().LocalMachine;
                    return _BaseKey;
                }
            } private IRegistryKey _BaseKey;
    
            public void ChangeBaseKey(IRegistryKey inBaseKey)
            {
                _BaseKey = inBaseKey;
            }
    
            #endregion
    

    Note: Notice that the Property is read only. Instead of enabling the set ability, a function is created to allow you to change the IRegistryKey instance. This is by design and keeps you from making a mistake such as BaseKey = BaseKey.OpenSubkey(“…”) and replacing the BaseKey.

    Note: You may want to look into the “Factory” design pattern.

  2. Change line 113 to use the BaseKey.
        IRegistryKey localKey = BaseKey.OpenSubKey(dotNetRegPath);
    

Step 4 – Download and Reference RhinoMocks in your Unit Test

You may have already done this when reading the previous post, if not do so now.

In this step you need to download RhinoMocks and reference it with your Unit Test project. If you don’t have a test project, create one.  Your release project won’t need it.

  1. Go to http://hibernatingrhinos.com/open-source/rhino-mocks and download RhinoMocks.
  2. Add RhinoMocks.dll

Step 5 – Mock IRegistryKey in your Unit Test

For this, you have to understand and know how to use RhinoMocks and this takes some learning. For this we need an example.

  1. Add a new class to your test project.
  2. Add a using statement:
    using&nbsp;Rhino.Mocks;
  3. Add code to create the Mock objects.I put these in separate functions because every test needed the exact same code.
    1. Mock the HKLM key and any calls made using it.
    2. Mock the registry sub key and any calls made using it.
    #region Test Helper Functions
            /// <summary>
            /// Mock to pretend to be this registry subkey:
            /// Hive:   HKLM
            ///
            /// No stubbing is preconfigured
            /// </summary>
            /// <returns>IRegistryKey</returns>
            private IRegistryKey CreateMockOfHKLM()
            {
                // Mock to pretend to be this registry key:
                // Hive:   HKLM
                IRegistryKey hklmMock = MockRepository.GenerateMock<IRegistryKey>();
                hklmMock.Stub(x => x.Name).Return("HKEY_LOCAL_MACHINE");
    
                return hklmMock;
            }
    
            /// <summary>
            /// Mock to pretend to be this registry subkey:
            /// Hive:   HKLM
            ///
            /// It has stubs preconfigured
            /// </summary>
            /// <returns>IRegistry that is a mock of HKLM with IIS Version stubs.</returns>
            private IRegistryKey CreateDotNetRegistryOpenSubKeyMock(string inSubkey, bool inIsInstalled = true, int? inSP = null)
            {
                // Mock to pretend to be this registry subkey:
                // Hive:   HKLM
                IRegistryKey hklmMock = CreateMockOfHKLM();
    
                // Allow to test a key that doesn't exist (null) or one that does.
                IRegistryKey dotNetMock = null;
                if (inIsInstalled)
                {
                    dotNetMock = CreateDotNetRegistryGetValueMock(inSubkey, inSP);
                }
    
                // Stubs using hklmMock to open and return this registry key
                // and return dotNetMock:
                hklmMock.Stub(x => x.OpenSubKey(inSubkey)).Return(dotNetMock);
    
                return hklmMock;
            }
    
            private IRegistryKey CreateDotNetRegistryGetValueMock(string inSubkey, int? inSP)
            {
                // Mock to pretend to be this subkey passed in:
                // Hive:   HKLM
                // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                IRegistryKey dotNetMock = MockRepository.GenerateMock<IRegistryKey>();
                dotNetMock.Stub(x => x.Name).Return(@"HKEY_LOCAL_MACHINE\" + inSubkey);
    
                // Stubs checking the available registry properties:
                // Hive:   HKLM
                // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                // Properties: "Install", "SP"
                dotNetMock.Stub(x => x.GetValueNames()).Return(new String[] { "Install", "SP" });
    
                // Stubs checking this registry:
                // Hive:   HKLM
                // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                // Property: Install
                // Value:  1 - If not installed the whole key shouldn't even exist so it should always be 1
                dotNetMock.Stub(x => x.GetValue("Install")).Return(1);
    
                if (null != inSP)
                {
                    // Stubs checking this registry:
                    // Hive:   HKLM
                    // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                    // Property: SP
                    // Value:    null or 1, 2, 3, ...
                    dotNetMock.Stub(x => x.GetValue("SP")).Return(inSP);
                }
                return dotNetMock;
            }
            #endregion
    
  4. Now go forth and mock all your code that uses the Registry.

Here is the final test file.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
using SystemInfo;
using SystemInterface.Microsoft.Win32;

namespace DotNetFrameworkTest
{
    /// <summary>
    ///This is a test class for DotNetFrameworkTest and is intended
    ///to contain all DotNetFrameworkTest Unit Tests
    ///</summary>
    [TestClass()]
    public class DotNetFrameworkTest
    {
        #region Constructor tests
        /// <summary>
        ///A test for DotNetFramework Constructor
        ///</summary>
        [TestMethod()]
        public void DotNetFrameworkConstructorTest()
        {
            DotNetFramework target = new DotNetFramework();
            Assert.IsNotNull(target);
        }
        #endregion

        #region IAccessTheRegistry interface items test
        /// <summary>
        ///A test for ChangeBaseKey
        ///</summary>
        [TestMethod()]
        public void BaseKeyAndChangeBaseKeyTest()
        {
            DotNetFramework target = new DotNetFramework(); // TODO: Initialize to an appropriate value
            IRegistryKey defaultBaseKey = target.BaseKey;
            IRegistryKey inBaseKey = MockRepository.GenerateMock<IRegistryKey>();
            target.ChangeBaseKey(inBaseKey);

            // Make sure the newly assigned is not the same as the original
            Assert.AreNotEqual(target.BaseKey, defaultBaseKey);

            // Make sure that the assignment worked
            Assert.AreEqual(target.BaseKey, inBaseKey);
        }
        #endregion

        #region FoundDotNet11 tests
        /// <summary>
        ///A test for FoundDotNet11 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet11_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET11_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet11;
            Assert.AreEqual(actual, expected);

            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET11_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET11_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet11 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet11_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET11_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet11;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET11_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET11_VERSION));
        }
        #endregion

        #region FoundDotNet20 tests
        /// <summary>
        ///A test for FoundDotNet20 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet20;
            Assert.AreEqual(actual, expected);

            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
        }
        #endregion

        #region FoundDOtNet20SP1 tests
        /// <summary>
        ///A test for FoundDotNet20SP1 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP1_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet20SP1;
            
            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP1 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP1_Test_KeyExistsWithoutSP1()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP1;
            
            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP1 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP1_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
        }
        #endregion

        #region FoundDOtNet20SP2 tests
        /// <summary>
        ///A test for FoundDotNet20SP2 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP2_Test_KeyExistsWithSP2()
        {
            bool isInstalled = true;
            int? sp = 2;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet20SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP2 mocking the key so it should return false because it only has SP1
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP2_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP2 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP2_Test_KeyExistsWithoutSP()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP2 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP2_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
        }
        #endregion

        #region FoundDotNet30 tests
        /// <summary>
        ///A test for FoundDotNet30 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet30;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
        }
        #endregion

        #region FoundDOtNet30SP1 tests
        /// <summary>
        ///A test for FoundDotNet30SP1 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP1_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet30SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP1 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP1_Test_KeyExistsWithoutSP()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP1 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP1_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
        }
        #endregion

        #region FoundDOtNet30SP2 tests
        /// <summary>
        ///A test for FoundDotNet30SP2 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP2_Test_KeyExistsWithSP2()
        {
            bool isInstalled = true;
            int? sp = 2;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet30SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP2 mocking the key so it should return false because it only has SP1
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP2_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP2 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP2_Test_KeyExistsWithoutSP()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP2 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP2_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
        }
        #endregion
        
        #region FoundDotNet35 tests
        /// <summary>
        ///A test for FoundDotNet35 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet35;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet35 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet35;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
        }
        #endregion

        #region FoundDOtNet35SP1 tests
        /// <summary>
        ///A test for FoundDotNet35SP1 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35SP1_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet35SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet35SP1 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35SP1_Test_KeyExistsWithoutSP()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet35SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet35SP1 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35SP1_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet35SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
        }
        #endregion

        #region FoundDotNet 4 Full tests
        /// <summary>
        ///A test for FoundDotNet4 (full) mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet4_Full_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET40_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet4;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet4 (full) mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet4_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET40_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet4;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION));
        }
        #endregion

        #region FoundDotNet4 Client tests
        /// <summary>
        ///A test for FoundDotNet4Client mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet4Client_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet4Client;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet4 (client) mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet4Client_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet4Client;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT));
        }
        #endregion

        #region HasDotNetFrameworkTest
        /// <summary>
        ///A test for HasDotNetFramework
        ///</summary>
        [TestMethod()]
        public void HasDotNetFrameworkTest()
        {
            // No need to test this as all properties test this
        }

        #endregion

        #region Test Helper Functions
        /// <summary>
        /// Mock to pretend to be this registry subkey:
        /// Hive:   HKLM
        /// 
        /// No stubbing is preconfigured
        /// </summary>
        /// <returns>IRegistryKey</returns>
        private IRegistryKey CreateMockOfHKLM()
        {
            // Mock to pretend to be this registry key:
            // Hive:   HKLM
            IRegistryKey hklmMock = MockRepository.GenerateMock<IRegistryKey>();
            hklmMock.Stub(x => x.Name).Return("HKEY_LOCAL_MACHINE");

            return hklmMock;
        }

        /// <summary>
        /// Mock to pretend to be this registry subkey:
        /// Hive:   HKLM
        /// 
        /// It has stubs preconfigured
        /// </summary>
        /// <returns>IRegistry that is a mock of HKLM with IIS Version stubs.</returns>
        private IRegistryKey CreateDotNetRegistryOpenSubKeyMock(string inSubkey, bool inIsInstalled = true, int? inSP = null)
        {
            // Mock to pretend to be this registry subkey:
            // Hive:   HKLM
            IRegistryKey hklmMock = CreateMockOfHKLM();

            // Allow to test a key that doesn't exist (null) or one that does.
            IRegistryKey dotNetMock = null;
            if (inIsInstalled)
            {
                dotNetMock = CreateDotNetRegistryGetValueMock(inSubkey, inSP);
            }

            // Stubs using hklmMock to open and return this registry key
            // and return dotNetMock:
            hklmMock.Stub(x => x.OpenSubKey(inSubkey)).Return(dotNetMock);
            
            return hklmMock;
        }

        private IRegistryKey CreateDotNetRegistryGetValueMock(string inSubkey, int? inSP)
        {
            // Mock to pretend to be this subkey passed in:
            // Hive:   HKLM
            // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
            IRegistryKey dotNetMock = MockRepository.GenerateMock<IRegistryKey>();
            dotNetMock.Stub(x => x.Name).Return(@"HKEY_LOCAL_MACHINE\" + inSubkey);

            // Stubs checking the available registry properties:
            // Hive:   HKLM
            // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
            // Properties: "Install", "SP"
            dotNetMock.Stub(x => x.GetValueNames()).Return(new String[] { "Install", "SP" });

            // Stubs checking this registry:
            // Hive:   HKLM
            // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
            // Property: Install
            // Value:  1 - If not installed the whole key shouldn't even exist so it should always be 1
            dotNetMock.Stub(x => x.GetValue("Install")).Return(1);

            if (null != inSP)
            {
                // Stubs checking this registry:
                // Hive:   HKLM
                // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                // Property: SP
                // Value:    null or 1, 2, 3, ...
                dotNetMock.Stub(x => x.GetValue("SP")).Return(inSP);
            }
            return dotNetMock;
        }
        #endregion

    }
}

Return to C# Unit Test Tutorial

Unit Testing code that touches the system

Unit Tests should be fast and simple and they should not touch the system. What we mean by touching the system is any code that actually changes the file system or registry of the build system that runs the Unit Tests. Also any code that touches a remote system such as a database or a web server as these remote system should not have to exist during a Unit Test.

Unit Test Presentation (using Open Office Impress)

Question: So if your code accesses the system, how do you test this code?

Answer: You use Interface-based design and a library that can mock that interface.

Well, it is not exactly simple.

Question: What if you are using some one elses code, such as standard C# libraries in the System or Microsoft namespaces?

Answer: Imagine you need to unit test code that touches the registry. You must do the following steps:

  1. Create an interface for accessing the registry that matches Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey (and you may have to create an interfaces for each object they need as well).
  2. Create a wrapper that wraps the Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey (again, you have to create a wrapper for each objects they need as well).
  3. Change your production code to use the interfaces and the wrappers instead of using the system code.  For example, if dealing with the Registry this involves Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey directly.Don’t use these objects directly, instead you use these objects:
    SystemInterface.Microsoft.Win32.IRegistry
    SystemInterface.Microsoft.Win32.IRegistryKey
    SystemWrapper.Microsoft.Win32.RegistryWrap
    SystemWrapper.Microsoft.Win32.RegistryKeyWrap
  4. Provide a method in your production code for replacing anywhere you use IRegistry or IRegistryKey with any object that implements the interface.
  5. In your Unit Test, mock any neededIRegistry and IRegistryKey objects.

The best solution, long-term, is that Microsoft adds interfaces to the standard .NET libraries and exposes these interfaces so a wrapper isn’t needed. If you agree, vote for this enhancement here: Implement interfaces for your objects so we don’t have use SystemWrapper.codeplex.com

However, since Microsoft hasn’t done this, you have to do it yourself. But all of this probably takes more time than your project will allow you to take, so I am going to try to get you there faster.
Step 1 and Step 2 are done for you, all you have to do is download the dll or source from here:
http://SystemWrapper.codeplex.com
Step 3 and 4 are not done for you but there are examples in the SystemWrapper project.
Step 5 can be done extremely quickly with a free (BSD Licensed) tool called RhinoMocks.
So the new steps become these:

Step 1 – Download SystemWrapper

  1. Go to http://SystemWrapper.codeplex.com and download the latest dll or the latest source.
  2. Copy the SystemInterface.dll and SystemWrapper.dll into your project (perhaps you already have a libs directory).
  3. Add references to these two dlls in your release code.
  4. Add a reference only to SystemInterface.dll in your Unit Test project.

Step 2 – Change your code to use Interfaces and Wrappers

  1. Find any place in your code where it touches the system. For example, if you touch the registry, find any place you call Registry or RegistryKey objects or reference Microsoft.Win32.
    Hint: Use the search feature in your IDE.
  2. Replace the reference with a reference to SystemWrapper and SystemInterfaces. For example, if replacingrRegistry code,
    SystemInterface.Microsoft.Win32
    SystemWrapper.Microsoft.Win32
  3. For any object that touches the system, change that object to be instantiated using the interface. For example, replace RegistryKey objects with IRegistryKey objects.

Step 3 – Allow for replacing the Interface-based objects

Create a property or function that allows you to replace the object you are mocking so you can pass in an object that is mocked.

Here is an example of how to do this when mocking a RegistryKey object using IRegistryKey.

  1. Implement the IAccessTheRegistry interface from the SystemInterface.Microsoft.Win32 namespace. Here is a sample implementation that uses lazy property injection:
            #region IAccessTheRegistry Members
    
            public IRegistryKey BaseKey
            {
                get { return _BaseKey ?? (_BaseKey = new RegistryWrap().LocalMachine); }
                internal set { _BaseKey value; }
            } private IRegistryKey _BaseKey;
    
            #endregion
    

    Notice that the setter is internal. This is because unit tests can usually access an internal method with InternalsVisibleTo. The internal set is hidden for code not in the same assembly and not included in InternalsVisibleTo.

Note: You may want to look into the “Factory” design pattern.

Step 4 – Download and Reference RhinoMocks in your Unit Test

In this step you need to download RhinoMocks and reference it with your Unit Test project. Your release project won’t need it.

  1. Go to http://hibernatingrhinos.com/open-source/rhino-mocks and download RhinoMocks.
  2. Add RhinoMocks.dll

Step 5 – Mock IRegistryKey in your Unit Test

For this, you have to understand and know how to use RhinoMocks and this takes some learning.

Instead of trying to explain this here, let’s go straight into the examples.

Examples

Forthcoming…

  1. Unit Testing Registry access with RhinoMocks and SystemWrapper
  2. Unit Testing File IO with RhinoMocks and SystemWrapper

Return to C# Unit Test Tutorial