Faking Private Properties or Indexers

To fake a private property or indexer, use one of the following specialized Isolate.NonPublic APIs:

Behavior Type

Description

NonPublic.Property

Fakes a private property

NonPublic.Indexer

Fakes a private indexer

Then use one of the following:

Behavior Type

Description

WhenGetCalled

Fakes the property getter (var x = aClass.Password)

WhenSetCalled

Fakes the property setter (myClass.Password = "typemock rocks";)

Syntax
C#

Isolate.NonPublic.Property.WhenGetCalled(fakeDependency, "PrivateProp").WillReturn(<value>);
Isolate.NonPublic.Property.WhenSetCalled(fakeDependency, "PrivateProp").IgnoreCall();

VB

Isolate.NonPublic.Property.WhenGetCalled(fakeDependency, "PrivateProp").WillReturn(<value>)
Isolate.NonPublic.Property.WhenSetCalled(fakeDependency, "PrivateProp").IgnoreCall()

Samples
Sample 1: Faking Values Returned from a Private Property

To set a behavior on a private get or set property, use the same Isolate.NonPublic function (that is NonPublicWillReturn) with get_PropertyName and set_PropertyName as the method name.

To set a behavior on a private indexer, use the same Isolate.NonPublic function (that is NonPublicWillReturn) with get_Item and set_Item as the method name.

You can set static properties by passing a type instead of an instance.

Indexers cannot be static.

C#

var fakeDependency = Isolate.Fake.Instance<Dependency>(Members.CallOriginal);
Isolate.NonPublic.Property.WhenGetCalled(fakeDependency, "PrivateProp").WillReturn(3);

VB

Dim fakeDependency = Isolate.Fake.Instance(Of Dependency)(Members.CallOriginal)
Isolate.NonPublic.Property.WhenGetCalled(fakeDependency, "PrivateProp").WillReturn(3)

Sample 2: Faking a Private Property when the Private Method Has Generic Arguments

The following sample shows how to fake a private property when the private method has generic arguments.

C#

//Syntax
Isolate.NonPublic.WhenCalled(fakeDependency, "PrivateProp").WithGenericArguments(typeof(MyClass)).WillReturn(<value>);

[TestMethod, Isolated]
public void PrivateGenericMethod_Return()
{
  Isolate.NonPublic.WhenCalled<Dependency>("PrivateCallGuardGeneric").WithGenericArguments(typeof(int)).WillReturn(3);
  var result = Dependency.CallsGuardGeneric<int>();
  Assert.AreEqual(3, result);
}

private static T PrivateCallGuardGeneric<T>()
{
  return default(T);
}

VB

'Syntax
Isolate.NonPublic.WhenCalled(fakeDependency, "PrivateProp").WithGenericArguments(GetType(MyClass)).WillReturn(<value>)

<TestMethod, Isolated>
Public Sub PrivateGenericMethod_Return()
    Isolate.NonPublic.WhenCalled(Of Dependency)("PrivateCallGuardGeneric").WithGenericArguments(GetType(Integer)).WillReturn(3)
    Dim result = Dependency.CallGuardGeneric(Of Integer)()
    Assert.AreEqual(3, result)
End Sub

Public Shared Function CallGuardGeneric(Of T)() As T
    Return PrivateCallGuardGeneric(Of T)()
End Function

Private Shared Function PrivateCallGuardGeneric(Of T)() As T
    Return Nothing
End Function