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
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Is it possible to mock chains contain fields, not properties?

e.g. ClassForTest.NestedClassForTest.GetString() where NestedClassForTest is public static field.

Thanks.
asked by tom3m (9.7k points)

5 Answers

0 votes
Hi,
Well the answer is yes and no. :roll:
in principle the following test works:

[Test]
public void TestChainWithField()
{
    using (RecordExpectations rec = new RecordExpectations())
    {
        ClassForTest.NestedClassForTest.GetString();
        rec.Return("Mock");
    }

    string actual = ClassForTest.NestedClassForTest.GetString();
    Assert.AreEqual("Mock", actual);
}


However you must remember that the access to NestedClassForTest is not mocked. What is mocked, is the call to the GetString method only and not the entire chain.
That said, i think this should not prevent you from testing this. You just need to pay close attention to what exactly is mocked and what is not, and verify it answer your testing needs.

:idea: you can use TypeMock Trace tool in order to see exactly which calls are being mocked.
answered by lior (13.2k points)
0 votes
>>Well the answer is yes and no.
Thats true.

It works different in case of public field and public property, I mean If I want mock the chain and not create real object, I must wrap public field with property. It was not clear from docs.
answered by tom3m (9.7k points)
0 votes
If I want mock the chain and not create real object, I must wrap public field with property.


Yes in general TypeMock can't mock fields. If you want to mock a field creation you can wrap it by a property.
Another possible solution for public fields is to create the MockObject on the outside and assign it to the field in the test setup.
answered by lior (13.2k points)
0 votes
>>Another possible solution for public fields is to create the MockObject on the outside and assign it to the field in the test setup.

Can you provide smaaaaal example? :)
answered by tom3m (9.7k points)
0 votes
Hi,
I meant something along the line of this:
[Test]
public void TestAssignmentWithField()
{
    MockObject mock = MockManager.MockObject<NestedClass>();
    NestedClass mockedInstance = mock.Object as NestedClass;
    using (RecordExpectations rec = new RecordExpectations())
    {
        mockedInstance.GetString();
        rec.Return("Mock");
    }

    ClassForTest.NestedClassForTest = mockedInstance;
    string actual = ClassForTest.NestedClassForTest.GetString();
    Assert.AreEqual("Mock", actual);
}
answered by lior (13.2k points)
...