Isolator’s VB API – Creating Fakes

So after the overview, let’s get down to business. How do we create fake instances?

Dim fakeProduct As Product = FakeInstance(Of Product)(Members.ReturnNulls)

Not surprised? Well, it is that simple. As with its C# sibling, we have the following options to create a fake, using the Members argument:

  • Members.ReturnRecursiveFakes – The default (also in C# from 5.2). Every method on this object returns a fake object. Every method on that fake object returns another fake object. And so on. You’ll never get a NullReferenceException again.
  • Members.ReturnNulls – Every method returns eiter a Null for reference types and 0 for value types.
  • Members.CallOriginal – Really a live object, all methods, including the constructors are called as implemented.
  • Members.MustSpecifyReturnValues – A strict policy. You’ll get a VerifyException if a method is called, but there was no behavior set on that method.

Except for the CallOriginal option, all others create a fake object, without calling its constructor. Note that if the constructor is not invoked, you might run into un-initialized fields later.

I would use the CallOriginal option only when I can’t use a real constructor, for items that have private constructors, or constructors that take arguments that I don’t care about or want to build.

Now, that I have a fake in my hand, I can set it’s behavior. But that’s for the next post. Let’s look at this code example of a VB Sub:

Private Shared Sub CreateProduct(ByVal name As String)
Dim product As New Product()
product.Name = name
End Sub

I want to test this method. But the Product is constructed (or “New”-ed) inside the method. We call this a future object. How do swap it with our fake one?

Dim fakeProduct As Product = FakeInstance(Of Product)()
SwapNextInstance(Of Product)(fakeProduct)

Again, no surprises to those who know the C# API. SwapNextInstance will cause the next New Product object to replace the fakeProduct.

Next time – on setting behavior.

TOP