JustMock

In elevated mode, you can use Telerik JustMock to mock non-public members and types. That is useful when you want to isolate calls to non-public members.

Note

This feature is available only in the commercial version of Telerik JustMock.

Refer to this topic to learn more about the differences between both the commercial and free versions of Telerik JustMock.

Important

To mock non-public members and types you first need to go to elevated mode by enabling Telerik JustMock from the menu. How to Enable/Disable Telerik JustMock?

Important

To interact with non-public members and types you will need to add the InternalVisibleTo property inside the AssemblyInfo.cs in your project, like this:

C# Copy imageCopy
[assembly: InternalsVisibleTo("YourTestProject")]

In the further examples we will use the following sample class to test:

C# Copy imageCopy
public class Foo
{
    private void DoPrivate()
    {
        throw new NotImplementedException();
    }
	
    private void DoPrivate(int arg)
    {
        throw new NotImplementedException();
    }
	
    public void DoPublic()
    {
        DoPrivate();
    }
	
    public void Execute(int arg)
    {
        DoPrivate(arg);
    }
	
    private int PrivateEcho(int arg)
    {
        return arg;
    }
	
    public int Echo(int arg)
    {
        return PrivateEcho(arg);
    }
	
    internal virtual void Do()
    {
        throw new NotImplementedException();
    }
	
    internal virtual string Value
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
}

Step by step example

First, create an instance of the type you want to test. To mock a non-public member use the Mock.NonPublic modifier and then add the arrange statement. In the arrange statement, first pass the target object to test, then the member name that you want to test as a string and eventually arguments to be passed in case you test a method.

C# Copy imageCopy
// Arrange
Foo foo = new Foo();

bool called = false;
Mock.NonPublic.Arrange(foo, "DoPrivate").DoInstead(() => called = true);

// Act
foo.DoPublic();

// Assert
Assert.IsTrue(called);  

Here we setup that a call to the DoPrivate method of the Foo class should set a local variable called. Thus we override the original method behavior with a one that we specify.

Mock Private Call with Matcher

Arrange a call to a private method accepting an argument that matches any integer value.

C# Copy imageCopy
// Arrange
Foo foo = new Foo();

// Act
Mock.NonPublic.Arrange<int>(foo, "PrivateEcho", Arg.AnyInt).Returns(1);

int actual = foo.Echo(5);
int expected = 1;

Assert.AreEqual(expected, actual);


Here we specify that PrivateEcho method called with any int argument will return 1. Acting is by calling it with 5 as argument. Finally, we verify that the return value is actually 1.

Mock Private Method With Overloads

Here we arrange a call to a private method with two overloads.

The following class will be used:

C# Copy imageCopy
internal class FooInternal
{
    private void pExecute(int arg1)
    {
        throw new NotImplementedException();
    }
	
    private void pExecute()
    {
        throw new NotImplementedException();
    }

    public void Execute( int arg1 )
    {
        pExecute( arg1 );
    }

    public void Execute()
    {
        pExecute();
    }
}
	

We mock the pExecute method that accepts an integer value as argument. We arrange it to set a local boolean variable to true once it is called with 10 as argument. After that we act by calling foo.Execute(10) and verify that called is true.

C# Copy imageCopy
// Arrange
FooInternal foo = new FooInternal();
bool called = false;
Mock.NonPublic.Arrange(foo, "pExecute", 10).DoInstead(() => called = true);

// Act
foo.Execute(10);

// Assert
Assert.IsTrue(called);
	

Mock Private Interface Implementation Method

This example shows how we can mock an explicit (not public) interface implementation method from current or base class.

The following classes will be used:

C# Copy imageCopy
public interface IManager
{
	object Provider { get; }
}

public class FooBase : IManager
{
	object IManager.Provider
	{
		get { throw new NotImplementedException(); }
	}
}

public class Bar : FooBase
{
	//...
}

We can now mock the IManager.Provider call in this way:

C# Copy imageCopy
var bar = Mock.Create<Bar>();  
const string expected = "dummy";
Mock.Arrange(() => ((IManager)bar).Provider).Returns("dummy");

Assert.AreEqual(expected, ((IManager)bar).Provider);

Mock Internal Virtual Method

Arrange a call to an internal virtual method.

C# Copy imageCopy
// Arrange
Foo foo = new Foo();

bool called = false;
Mock.Arrange(() => foo.Do()).DoInstead(() => called = true);

// Act
foo.Do();

// Assert
Assert.IsTrue(called);  

Note that in the arrange statement we don't use a mock of Foo, but the actual instance.

Mock Internal Virtual Property Get And Set

Arrange a call to an internal virtual property.

C# Copy imageCopy
// Arrange
Foo foo = new Foo();

Mock.Arrange(() => foo.Value).Returns("ping");

// Act
string actual = foo.Value;

// Assert
Assert.AreEqual("ping", actual);  

Note that in the arrange statement we don't use a mock of Foo, but the actual instance.

Follows an example of mocking internal virtual property set. We override the actual implementation by arranging that the foo.Value must be called with certain value.

C# Copy imageCopy
// Arrange
Foo foo = Mock.Create<Foo>();

Mock.ArrangeSet(() => foo.Value = "ping").MustBeCalled();

// Act
foo.Value = "ping";

// Assert
Mock.Assert(foo);

Mock Private Static Method

The following example shows how to mock a private static method.

We use the following class:

C# Copy imageCopy
internal class FooInternalStatic
{
    private static int EchoPrivate(int arg1)
    {
        throw new NotImplementedException();
    }

    public static int Echo(int arg1)
    {
        return EchoPrivate(arg1);
    }
}
	

The method we arrange is FooInternalStatic.EchoPrivate().

C# Copy imageCopy
// Arrange
Mock.NonPublic.Arrange<FooInternalStatic, int>("EchoPrivate", 10);

// Act
FooInternalStatic.Echo(10);

// Assert
Mock.NonPublic.Assert<FooInternalStatic, int>("EchoPrivate", 10);
	

We call the Echo method, but its implementation calls the EchoPrivate method, so our assertion passes.

Mock Internal Class

Let's see an example of how to mock an internal class from .NET framework. Consider the System.Net.HttpRequestCreator class which is internal, but has a public interface System.Net.IWebRequestCreate. Here we mock its Create method.

C# Copy imageCopy
// Arrange
string typeName = "System.Net.HttpRequestCreator";

var httpRequestCreator = Mock.Create(typeName);

bool called = false;

Mock.NonPublic.Arrange(httpRequestCreator, "Create", ArgExpr.IsAny<Uri>()).DoInstead(() => called = true);

// Act
System.Net.IWebRequestCreate iWebRequestCreate = (System.Net.IWebRequestCreate)httpRequestCreator;

iWebRequestCreate.Create(new Uri("http://www.telerik.com"));

// Assert
Assert.IsTrue(called);

Note the use of ArgExpr.IsAny<Uri>() - as we mock a non public call, we need to know the type of the argument to resolve the method. Thus, instead of using Arg, like we do in most of the other cases, we must use ArgExpr.

Important
To mock internal type, your assembly name must be fully qualified according to the framework design rules, i.e. assembly name = namespace. Note that you can't mock types from mscorlib in this way. We do a hierarchical search to find the proper qualified name as in the above example. System.Net.HttpRequestCreator is found in the System assembly, not in System.Net.

Mock Protected Member

To show how the mocking of protected members is being done, we will use the following class:

C# Copy imageCopy
    public class Foo
    {
        protected virtual void Load()
        {
            throw new NotImplementedException();
        }

        protected virtual int IntValue
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public virtual void Init()
        {
            Load();
        }
    }
	

To mock protected members in JustMock, we use the same method and logic, as for the rest non-public types, shown above:

First we will arrange that our IntValue() method should never occur, like this:

C# Copy imageCopy
        [TestMethod]
        public void ShouldAssertOccrenceForNonPublicFunction()
        {
            var foo = Mock.Create<Foo>(Behavior.CallOriginal);

            Mock.NonPublic.Assert<int>(foo, "IntValue", Occurs.Never());
        }
	

The second test will test if our protected Load() method is actually been called, when Init() is initiated.

C# Copy imageCopy
        [TestMethod]
        public void ShouldMockProtectedVirtualMembers()
        {
            var foo = Mock.Create<Foo>(Behavior.CallOriginal);

            Mock.NonPublic.Arrange(foo, "Load").MustBeCalled();

            foo.Init();

            Mock.Assert(foo);
        }
	

Important
To mock protected type, your assembly name must be fully qualified according to the framework design rules, i.e. assembly name = namespace. Note that you can't mock types from mscorlib in this way.

See Also