Interested in a
Personal Demo ?


Name* :
Please Enter your Name
Company E–Mail* :
Please Enter a Valid Email

Testimonials


"I find a new use for Typemock each time I use it... It's not often a product fills a gap so well… I was impressed. It takes care of a big hole in unit testing"
John Spano, CTO and Co-Founder, NeoTekSystems
Success stories

PurchaseOptions


US Toll Free
877–634–0165
Outside US
+44–2035146725
Get your printable quote
Buy online starting from $249

 

Basic mocking and faking with Typemock Isolator

This section takes you through some of the basics of Typemock Isolator

Don't forget that to use Typemock Isolator, you need to reference TypeMock Isolator C# APIs and TypeMoke Isolator Core DLL (via the .NET tab), or add the actual files named TypeMock.dll and TypeMock.Arrange.Act.Assert.Dll (via the Browse tab).

Faking Objects

Creating Fake Objects

Fake objects replace real objects in the test. We create fake objects to isolate objects that represent an external dependancy in your test. Their behavior is set up using Isolate.WhenCalled() and verified using Isolate.Verify.

To create a fake object, use the Isolate.Fake.Instance() method:

RealLogger fake = Isolate.Fake.Instance();

Fake objects can be created with a few predefined behaviors, that set the fake object's default behavior. You define the behavior types by passing a Members enum parameter toIsolate.Fake.Instance(). The possible behavior types are:

Members.ReturnRecursiveFake is the default fake object behavior. This means that calling Isolate.Fake.Instance() is the same as passing in Members.ReturnRecursiveFake.

Members.ReturnRecursiveFake behavior is a powerful faking tool, automatically faking chained calls even several levels down the object model. No need to explicitly fake return values and behavior for each hierarchy level.


In this example, the fake RealLogger we create calls GetSon() which in turn returns another a Son object on which another call is made:

[TestMethod]
[Isolated]
public void RecursiveStubWithExpectationOnSecondLevel ()
{
    / Arrange 
    RealLogger fake = Isolate.Fake.Instance(Members.ReturnRecursiveFake);
    Isolate.WhenCalled(() => fake.GetSon().DoSomething()).WillReturn(10);

    / Act 
    Logger son = fake.GetSon();
    son.DoSomething();

    / Assert 
    Isolate.Verify.WasCalledWithAnyArguments(() => fake.GetSon().DoSomething());
}

 

Future Instances

Sometimes we want fake the runtime behavior for objects instantiated in the code under test, also known as 'Future instance'. We set up the objects as shown above, to be swapped with the future object at the time of its creation. This is done using the Isolate.Swap.NextInstance().With() method.

public void FutureInstance_VerifyMethodWasCalledAndStubbed ()
{
    / Arrange 
    RealLogger fake = Isolate.Fake.Instance();
    / replace a future instance of RealLogger with the fake object we created
    Isolate.Swap.NextInstance().With(fake); 
    / set up additional fake object behavior
    Isolate.WhenCalled(() => fake.Increment()).IgnoreCall();
 
}

 

Controlling Behavior

Method Behavior

When you create fake objects, all method calls are handled according to its default behavior, specified on creation. You can set specific method's behavior by using Isolate.WhenCalled():

RealLogger fake = Isolate.Fake.Instance(); 
Isolate.WhenCalled(() => fake.Increment()).CallOriginal();

 

Isolate.WhenCalled() sets up completing statements that specify the desired method behavior, such as:

Isolate.WhenCalled() is strongly typed, which enforces correct use, for example:

Isolate.WhenCalled(() => fake.ReturnInt()).WillReturn(10);    / this is fine 
Isolate.WhenCalled(() => fake.ReturnInt()).WillReturn("ten");/ this will not compile

Static Method Behavior

Static methods are called on class types, not on fake instances, so there is no creation involved when setting up behavior for fake static method. Instead, we use Isolate.Fake.StaticMethods():

Isolate.Fake.StaticMethods();

 

Static classes cannot be passed as type arguments to StaticMethods(), so an overload is provided to pass them as type parameters:

Isolate.Fake.StaticMethods(typeof(StaticClassToFake));

For example, here's how you test static methods:

[TestMethod]
[Isolated]
public void TestStaticMethods()
{
    / define static method faking behavior for LoggerFactory 
    Isolate.Fake.StaticMethods(Members.CallOriginal);
    / define specific faking behavior for a chained call starting with static call
    Isolate.WhenCalled(() => LoggerFactory.GetLogger().GetSon().DoSomething()).WillReturn(10);

    Assert.AreEqual(10, LoggerFactory.GetLogger().GetSon().DoSomething());

    / Verify a static call was made
    Isolate.Verify.WasCalledWithAnyArgumnets(() => LoggerFactory.GetLogger().GetSon());
} 

 

Faking Behavior for Live Objects

A live object is a test object which has been instantiated normally, not through Isolator. When you only want to modify an object's behavior for a specific method call, just fake the specific behavior using Isolate.Fake.Instance():

RealLogger logger = new RealLogger(); / this is a normal "live" object
Isolate.WhenCalled(() => logger.Log("message")).IgnoreCall(); / ignore only the Log method

 

Faking Calls According to Method's Arguments

Custom behavior can be set based on arguments. This example shows you how to use exact argument matching using WhenCalled(() => ...).WithExactArguments(). The behavior specified after WithExactArguments() will only happen when the arguments in the call exactly match to the arguments passed to WhenCalled().

For example:

[TestMethod, Isolated]
public void FakeReturnValueByMethodArgs()
{
    var fake = Isolate.Fake.Instance();     / MethodReturnInt will return 10 when called with arguments 3, "abc"     Isolate.WhenCalled(()=> fake.MethodReturnInt(3, "abc")).WithExactArguments().WillReturn(10);     / MethodReturnInt will return 50 when called with arguments 3, "xyz"     Isolate.WhenCalled(()=> fake.MethodReturnInt(3, "xyz")).WithExactArguments().WillReturn(50);      Assert.AreEqual(10, fake.MethodReturnInt(3, "abc"));     Assert.AreEqual(50, fake.MethodReturnInt(3, "xyz")); }

 
As you can see, we set the return value of MethodReturnInt to 10 only when the arguments are 3 and "abc", and set the return value of MethodReturnInt to 50 only when the arguments are 3 and "xyz".

Verifying Behaviors

When writing unit tests, you may want to make sure that specific calls were made or correct parameters were passed into function calls. This is easily done with Isolate.Verify with a completing verification statement.

Verification is performed on fake objects and goes over the information collected during the test execution for them.

  

 

How to Start Unit Testing .NET Projects  Download Free Trial    Basic unit testing: Mocking and
Faking
     

Free Webinar: Triumph Over Legacy Code Writing Your First Unit Test in C# Difference Between Integration Tests & Unit Tests