Learn>Examples

Examples - How Tos

Summary

The following examples show you how to implement Typemock Isolator in your software code and write your unit tests faster and easier.

Section 1 – Mock Patterns

  • Basic .NET mock patterns
    • Using test decorators and Natural Mocks™
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      // Record methods here } // Run Test

      // Optional assertions
      Assert.AreEqual();
      }
      }
    • Using test decorators and Reflective Mocks
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks

      // Run Test

      // Optional assertions
      Assert.AreEqual();
      }
      }
  • Mocking one instance - Mocking .NET code
    • Using Natural Mocks™
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      // Record methods here ClassToIsolate mockedInstance = new ClassToIsolate();
      mockedInstance.Method();
      } // END RECORD STAGE // Run Test
      ClassUnderTest test = new ClassUnderTest();
      test.RunMethod();
      // These statements are run in RunMethod() //- ClassToIsolate mockedInstance = new ClassToIsolate();
      //- mockedInstance.Method();
      }
      }
    • Using Reflective Mocks
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks Mock mock = MockManager.Mock<ClassToIsolate>();
      mock.ExpectCall("Method");

      // Run Test ClassUnderTest test = new ClassUnderTest();
      test.RunMethod();
      // These statements are run in RunMethod() //- ClassToIsolate mockedInstance = new ClassToIsolate();
      //- mockedInstance.Method();
      }
      }
  • Mocking a type (all instances)
    • Using Natural Mocks™
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      recorder.MockAllInstances = true;
      ClassToIsolate mockedInstance = new ClassToIsolate();
      mockedInstance.Method();
      recorder.RepeatAlways();
      } // END RECORD STAGE // Run Test
      ClassUnderTest test = new ClassUnderTest();
      test.RunMethod();
      // Multiple 'new' run in RunMethod() //- ClassToIsolate mockedInstance = new ClassToIsolate();
      //- mockedInstance.Method();
      //- ClassToIsolate mockedInstance2 = new ClassToIsolate();
      //- mockedInstance2.Method();
      }
      }
    • Using Reflective Mocks
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks Mock mock = MockManager.MockAll<ClassToIsolate>();
      mock.ExpectCall("Method");

      // Run Test ClassUnderTest test = new ClassUnderTest();
      test.RunMethod();
      // Multiple 'new' run in RunMethod() //- ClassToIsolate mockedInstance = new ClassToIsolate();
      //- mockedInstance.Method();
      //- ClassToIsolate mockedInstance2 = new ClassToIsolate();
      //- mockedInstance2.Method();
      }
      }
  • Creating a mocked object from an interface/abstract class
    • Using Natural Mocks™
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks IInterfaceToMock mockedInterface = RecorderManager.CreateMockedObject<IIsolated>();
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      // Record Method by using mockedInterface mockedInterface.Method(); } // Run Test (pass mockedInterface)
      ClassUnderTest test = new ClassUnderTest(mockedInterface);
      test.RunMethod();
      }
      }
    • Using Reflective Mocks
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks MockObject<IInterfaceToMock> mockInterface = MockManager.MockObject<IInterfaceToMock>();
      mockInterface.ExpectCall("Method");

      // Run Test (pass mockInterface) ClassUnderTest test = new ClassUnderTest(mockInterface.Object);
      test.RunMethod();
      }
      }
  • Stubbing a type
    • Using Natural Mocks™
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      recorder.VerifyMode = VerifyMode.PassIfNotCalled;
      // Record methods here } // Run Test
      ClassUnderTest test = new ClassUnderTest();
      test.RunMethod();
      }
      }
    • Using Reflective Mocks
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithMock()
      {
      // Setup mocks Mock mock = MockManager.Mock<ClassToIsolate>();
      m.StartBlock(VerifyMode.PassIfNotCalled);
      // Set Expectation here m.EndBlock(); // Run Test
      ClassUnderTest test = new ClassUnderTest();
      test.RunMethod();
      }
      }
  • Testing asynchronous code
  • [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks(Timeout=4000)] // Verify that all expected calls where made public void TestWithMock()
    {
    // Setup mocks and Run Test
    }
    }

Section 2 – Faking Method Calls

  • Mocking a public static method
    [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks]
    public void TestWithNatural()
    {
    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
    ClassToIsolate.StaticMethod();
    }
    }

    [Test]
    [VerifyMocks]
    public void TestWithReflective()
    {
    Mock mock = MockManager.Mock<ClassToIsolate>();
    mock.ExpectCall("StaticMethod");
    }

    }
  • Mocking a public instance method
    [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks]
    public void TestWithNatural()
    {
    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
    ClassToIsolate mockedInstance = new ClassToIsolate();
    mockedInstance.InstanceMethod();
    }
    }

    [Test]
    [VerifyMocks]
    public void TestWithReflective()
    {
    Mock mock = MockManager.Mock<ClassToIsolate>();
    mock.ExpectCall("InstanceMethod");
    }
    }
  • Mocking a private method
    [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks]
    public void TestWithReflective()
    {
    Mock mock = MockManager.Mock<ClassToIsolate>();
    mock.ExpectCall("PrivateMethod");
    }

    [DeploymentItem("HowTo.exe")]
    [TestMethod]
    [VerifyMocks]
    public void TestWithNatural_VisualStudioAccessors()
    {
    object target = PrivateMethods.ClassToIsolateAccessor.CreatePrivate();
    PrivateMethods.ClassToIsolateAccessor accessor = new PrivateMethods.MClassToIsolateAccessor(target);

    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {

    accessor.PrivateMethod();
    }
    }
    }
  • Mocking properties
    [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks]
    public void TestWithNatural()
    {
    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
    ClassToIsolate mockedInstance = new ClassToIsolate();
    mockedInstance.MyProperty = 6;
    recorder.ExpectAndReturn(mockedInstance.MyProperty, 5);

    }
    }

    [Test]
    [VerifyMocks]
    public void TestWithReflective()
    {
    Mock mock = MockManager.Mock<ClassToIsolate>();
    mock.ExpectSet("MyProperty");
    mock.ExpectGet("MyProperty", 5);

    }
    }
  • Mocking indexers
    [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks]
    public void TestWithNatural()
    {
    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
    ClassToIsolate mockedInstance = new ClassToIsolate();
    mockedInstance[5] = "any-value";
    recorder.ExpectAndReturn(mockedInstance[5], "fake-value");
    }
    }

    [Test]
    [VerifyMocks]
    public void TestWithReflective()
    {
    Mock mock = MockManager.Mock<ClassToIsolate>();
    mock.ExpectSetIndex();
    mock.ExpectGetIndex("fake-value");

    }
    }
  • Mocking generics
    • Mocking a specific generic type
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate<int> mockedInstance = new ClassToIsolate<int>();
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.Mock<ClassToIsolate<int>();
      }
      }
    • Mocking unspecified (all) generic types
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.Mock(typeof(GenericClassToIsolate));
      }
      }
    • Mocking a specific generic method
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate mockedInstance = new ClassToIsolate();
      mocked.GenericMethod<int>();
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.Mock<ClassToIsolate>();
      mock.ExpectCall("GenericMethod", Generic.Method<int>());
      }
      }
    • Mocking unspecified (all) generic methods
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.Mock(typeof(ClassToIsolate));
      mock.ExpectCall("GenericMethod");
      }
      }
  • Mocking and firing events
  • [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks]
    public void TestWithNatural()
    {
    View fakeView = RecorderManager.CreateMockedObject<View>();
    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
    fakeView.Changed += null;
    }
    // Wire View to model model.SetView(fakeViewMock.Object); // Fire Changed event we can test if our model reacts to event RecorderManager.LastMockedEvent.Fire(this, null);
    }

    [Test]
    [VerifyMocks]
    public void TestWithReflective()
    {
    MockObject<View> fakeViewMock = MockManager.MockObject<View>();
    MockedEvent handle = fakeViewMock.ExpectAddEvent("Changed");

    // Wire View to model model.SetView(fakeViewMock.Object); // Fire Changed event we can test if our model reacts to event handle.Fire(this, null);
    }
    }

Section 3 – Setting Expectations

  • Returning fake values
    • Setting return values
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod();
      recorder.Return("fake-value");
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.MockAll<ClassToIsolate>();
      mock.ExpectAndReturn("StaticMethod", "fake-value");
      }
      }
    • Repeating return values
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod();
      recorder.Return("fake-value").Repeat(3);
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.MockAll<ClassToIsolate>();
      mock.ExpectAndReturn("StaticMethod", "fake-value", 3 /* repeat */);
      }
      }
    • Returning values regardless of the number of times the method was called (stub)
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod();
      recorder.Return("fake-value").RepeatAlways();
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.MockAll<ClassToIsolate>();
      mock.AlwaysReturn("StaticMethod", "fake-value");
      }
      }
    • Returning values of out and ref arguments
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      string fakeOutValue = "fake-out-value";
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod(out fakeOutValue);
      recorder.Return("fake-value");
      }
      //Test Execution
      string OutValue = "supplied-out-value";
      ClassToIsolate.StaticMethod(outValue);
        Assert.AreEqual("fake-out-value",outValue); //will succeed
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.Mock(typeof(ClassToIsolate));
      mock.ExpectAndReturn("StaticMethod", "fake-value").Args(new Assign("fake-out-value"));
      //Test Execution
      string OutValue = "supplied-out-value";
      ClassToIsolate.StaticMethod(outValue);
        Assert.AreEqual("fake-out-value",outValue); //will succeed
         }
      }
    • Returning dynamic values that change
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      public static object MyReturnValue(object[] parameters, object context)
      {
      // Logic goes here if ((bool)parameters[0] == false)
      {
      return 0;
      }
      return 1;
      }

      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod();
      recorder.Return(new DynamicReturnValue(MyReturnValue));
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.Mock(typeof(ClassToIsolate));
      mock.ExpectAndReturn("StaticMethod", new DynamicReturnValue(MyReturnValue));
      }
      }
  • Injecting faults
    [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks]
    public void TestWithNatural()
    {
    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
    ClassToIsolate.StaticMethod();
    recorder.Throw(new NullReferenceException());
    }
    }

    [Test]
    [VerifyMocks]
    public void TestWithReflective()
    {
    Mock mock = MockManager.Mock<ClassToIsolate>();
    mock.ExpectAndThrow("StaticMethod", new NullReferenceException());
    }
    }
  • Validating arguments of mocked methods
    • Checking the values of arguments passed
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod(5,6);
      recorder.CheckArguments();
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.MockAll<ClassToIsolate>();
      mock.ExpectCall("StaticMethod").Args(5, 6);
      }
      }
    • Using other constraints to check the arguments passed
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod("");
      recorder.CheckArguments(Check.IsEqualIgnoreCase("typemock"));
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.MockAll<ClassToIsolate>();
      mock.ExpectCall("StaticMethod").Args(Check.IsEqualIgnoreCase("typemock"));
      }
      }
    • Checking ref arguments
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      string fakeOutValue = "fake-out-value";
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod(ref fakeOutValue);
      recorder.Return("fake-value").CheckArguments("in-value");
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.Mock(typeof(ClassToIsolate));
      mock.ExpectAndReturn("StaticMethod", "fake-value").
      Args(new Assign("fake-out-value")).AndCheck("in-value");
      }
      }
    • Checking arguments without faking the method
      [TestFixture]
      [ClearMocks]
      public class TestClass
      {
      [Test]
      [VerifyMocks]
      public void TestWithNatural()
      {
      using (RecordExpectations recorder = RecorderManager.StartRecording())
      {
      ClassToIsolate.StaticMethod(5,6);
      recorder.CallOriginal().CheckArguments();
      }
      }

      [Test]
      [VerifyMocks]
      public void TestWithReflective()
      {
      Mock mock = MockManager.MockAll<ClassToIsolate>();
      mock.ExpectUnmockedCall("StaticMethod").Args(5, 6);
      }
      }
  • Faking calls based on arguments
    [TestFixture]
    [ClearMocks]
    public class TestClass
    {
    [Test]
    [VerifyMocks]
    public void TestWithNatural()
    {
    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
    ClassToIsolate.StaticMethod(5);
    recorder.Return(3).WhenArgumentsMatch();

    ClassToIsolate.StaticMethod(10);
    recorder.Return(4).WhenArgumentsMatch();
    }
    }

    [Test]
    [VerifyMocks]
    public void TestWithReflective()
    {
    Mock mock = MockManager.Mock<ClassToIsolate>();
    mock.ExpectAndReturn("StaticMethod", 3).When(5);
    mock.ExpectAndReturn("StaticMethod", 4).When(10);
    }
    }

Section 4 – Operability

  • Running Typemock Isolator with nunit-gui and using Typemock Runner
    [TypemockPath]\TMockRunner.exe [NunitPath]\bin\nunit.exe test-assembly
    Alternative way see Adrian suggestion
  • Running using NANT
    <?xml version="1.0"?>
    <project name="Typemock Examples" default="test" basedir=".">
    <property name="nunit" value="C:\Program Files\NUnit\bin\nunit-console.exe" />
    <property name="typemock.dir" value="C:\Program Files\Typemock\Typemock Isolator" />

    <target name="test">
    <!-- Dynamically load Isolator task. -->
    <loadtasks assembly="${typemock.dir}\Typemock.NAntBuild.dll" />
    <Typemock Isolatortart/>
    <exec program="${nunit}" failonerror="false">
    <arg value="Tests.dll" />
    </exec>
    <Typemock Isolatortop/>
    </target>
    </project>
  • Running using MSBuild
    <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
    <TypemockLocation>C:\Program Files\Typemock\Typemock.NET</TypemockLocation>
    <NUnit>"C:\Program Files\NUnit\bin\nunit-console.exe"</NUnit>
    </PropertyGroup>

    <Import Project ="$(TypemockLocation)\MSBuildSchema\Typemock.MSBuild.Tasks"/>
    <Target Name="TestWithTypemock">
    <Typemock Isolatortart/>
    <Exec ContinueOnError="true" Command="$(NUnit) Test.dll"/>
    <Typemock Isolatortop/>
    </Target>
    </Project>

Learn More

Promote Typemock

  • Put the Verified with Typemock logo on your Site

    Verified With TypeMock


Comments? Write to Webmaster
Copyright © Typemock Ltd 2004-2008. All Rights Reserved | Legal