Sample 1: Testing non-query
Original Method

The following sample shows a method that creates a new Entity of a Blog and adds it to the DataBase:

C#

public static void AddBlog(string name)
{
  using (var database = new BloggingContext())
  {
    //Create and save a new Blog 
    var blog = new Blog { Name = name };
    database.Blogs.Add(blog);
    database.SaveChanges();
  }
}

VB

Public Shared Sub AddBlog(name As String)
    Using database = New BloggingContext()
        'Create and save a new Blog 
        Dim blog = New Blog() With {
            .Name = name
        }
        database.Blogs.Add(blog)
        database.SaveChanges()
    End Using
   End Sub
End Class

Typemock Isolator Features Used

Swap Future Instance

Replacing Collections

Changing methods behavior

Scenario

1. Get a handle for future BloggingContext class with its original methods.

2. Set all calls to the method BloggingContext.Add to an alternative implementation: add the Blog to the fake list instead of the DataBase.

3. Set all calls to the method BloggingContext.SaveChanges to be ignored and its return value to 1.

4. Call the Program.GetAllBlogs method.

5. Check the list and verify that BloggingContext.SaveChanges had been called.

Code
C#

[TestMethod, Isolated]
public void AddFakeEntityToDB_EntityIsInTheDB()
{
  List<Blog> fakeDb =  new List<Blog>();

  //Get a handle for future instance of BloggingContext that will be created 
  var contextHandle = Isolate.Fake.NextInstance<BloggingContext>(Members.CallOriginal);
  
  //Changing the Add and SaveChanges methods behavior 
  Isolate.WhenCalled(() => contextHandle.Blogs.Add(null)).DoInstead(context => 
  {
      var blog = context.Parameters[0] as Blog;
      fakeDb.Add(blog);
      return blog;
  });
  Isolate.WhenCalled(() => contextHandle.SaveChanges()).WillReturn(1);
  
  //Call the method that is under test
  Program.AddBlog("test");
  
  //Assert
  Assert.AreEqual("test", fakeDb[0].Name);
  Isolate.Verify.WasCalledWithAnyArguments(() => contextHandle.SaveChanges());
}

VB

<TestMethod(), Isolated()>
Public Sub AddFakeEntityToDB_EntityIsInTheDB()
    Dim fakeDb As List(Of Blog) = New List(Of Blog)()
	
    'Get a handle for future instance of BloggingContext that will be created 
    Dim contextHandle = Isolate.Fake.NextInstance(Of BloggingContext)(Members.CallOriginal)
    Isolate.WhenCalled(Function() contextHandle.SaveChanges()).WillReturn(1)
   
    'Changing the Add method and the SaveChanges behavior 
    Isolate.WhenCalled(Function() contextHandle.Blogs.Add(Nothing)).DoInstead(Function(context)
             Dim blog = TryCast(context.Parameters(0), Blog)
             fakeDb.Add(blog)
             Return blog

    End Function)

    'Call the method that is under test
    Program.AddBlog("test")
	
    'Assert
    Assert.AreEqual("test", fakeDb(0).Name)
    Isolate.Verify.WasCalledWithAnyArguments(Function() contextHandle.SaveChanges())

End Sub