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
Hello,

I have certain issue when I try to access private field using generated accessors and faked object. Non public accessor internally uses PrivateObject class and my test below is base on it.

I have an abstract class which implement some functionality for all future parents. The example of the class below:

public abstract class TestPrivate
{
    private string testField;

    //functionality in base class which should be tested 
    public virtual string DoWorkInBaseClass()
    {
        return testField;
    }
}


Then I tried to test this functionality without any concrete class implementation. I wrote the following test:

[TestMethod]
[Isolated]
public void IsolatedPrivateFieldFailureTest()
{
    string expectedValue = "test string to private fields";
    TestPrivate obj = Isolate.Fake.Instance<TestPrivate>(Members.CallOriginal);
    PrivateObject privateObj = new PrivateObject(obj);
    privateObj.SetField("testField", expectedValue);

    //Test some functionality in base class
    string actual = obj.DoWorkInBaseClass();

    Assert.AreEqual(expectedValue, actual);
}


This test fails with FieldMissingException. In real tests I uses generated private fields accessors which internally use PrivateObject class and fails with the same error.

BTW: if I add to the TestPrivate class abstract modifier the test above passes (but in this case Isolate framework just creates a real instance of TestPrivate class).

Do you have any ideas how can write my test with Isolate in this case?

TIA,
Grammer
asked by grammer (1.8k points)

2 Answers

0 votes
Hi,

You can use Isolator ObjectState instead PrivateObject. ObjectState supports working on fields of abstract clases.

[TestMethod]
[Isolated]
public void IsolatedPrivateFieldFailureTest()
{
    string expectedValue = "test string to private fields";
    TestPrivate obj = Isolate.Fake.Instance<TestPrivate>(Members.CallOriginal);
     
    ObjectState.SetField(obj, "testField", expectedValue);

    //Test some functionality in base class 
    string actual = obj.DoWorkInBaseClass();

    Assert.AreEqual(expectedValue, actual);
}


Best Regards,
Elisha
Typemock Support[/b]
answered by Elisha (12k points)
0 votes
Elisha,

ObjectState is exactly what I need. Great Thanks!

The only comment it will be great to add generic (SetField, GetField) methods in order to avoid cast.

Thanks again,
Grammer
answered by grammer (1.8k points)
...