chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
How can I mock private/readonly variables of a class. Thanks
asked by sony (7.2k points)

5 Answers

0 votes
Hi Sony,

You can use Isolator ObjectState API (You'll need to reference Typemock.dll)
ObjectState has two static methods:
SetField(object obj, string fieldName, object value)
And
GetField(object obj, string fieldName)

Usage example:
public class A
{
    private int _x;
    public int GetX
    {
        get { return _x; }
    }
}
[Test]
public void TestPrivate()
{
    A a = new A();
    ObjectState.SetField(a, "_x", 5);
    Assert.AreEqual(5, a.GetX);
}


Please let me know if it helps.
answered by ohad (35.4k points)
0 votes
Hi Ohad,

Thanks for your reply. As per our understanding 'ObjectState.SetField' is used for setting value of a private variable.
Our requirement is to initialize readonly private variable. We are ignoring the constructor call but want to initialize readonly variables which are being used in the method we want to test. Kindly suggest some way to achieve the above. Thanks
answered by sony (7.2k points)
0 votes
Hi Sony,

This will work also for readonly fields :)

public class A
{
    private readonly int _x = 1;
    public int GetX
    {
        get { return _x; }
    }
}

[Test]
public void Method_Scenario_() 
{
    A a = new A();
    ObjectState.SetField(a, "_x", 5);
    Assert.AreEqual(5, a.GetX);
}
answered by ohad (35.4k points)
0 votes
Hi Ohad,

Thanks for your reply. As per our understanding 'ObjectState.SetField' is used for setting value of a private variable.
Our requirement is to initialize readonly private variable. We are ignoring the constructor call but want to initialize readonly variables which are being used in the method we want to test. Kindly suggest some way to achieve the above. Thanks
answered by sony (7.2k points)
0 votes
Hi Sony,

Please notice that in the example code in my previous post the field is readonly. :)
ObjectState.SetField will work in that case.
answered by ohad (35.4k points)
...