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
+1 vote

I'm trying to mock a generic class such that the constructor only assigns one of the generic properties, as follows:

using System;

using TypeMock;
using TypeMock.ArrangeActAssert;

namespace RD.MobileClient.Core.BDDTests
{
    class GenericClass<T>
    {
        public T Foo { get; private set; }

        public Object Bar { get; private set; }

        public GenericClass(T foo, Object bar)
        {
            this.Foo = foo;
            this.Bar = bar;
        }
    }
    class Test
    {
        public Test()
        { 
            // Also tried with Members.CallOriginal and Members.MustBeSpecified. Same problem.
            GenericClass<string> fake_generic_class = Isolate.Fake.AllInstances<GenericClass<string>>(Members.ReturnRecursiveFakes, ConstructorWillBe.Ignored);
            
            MockManager.GetMockOf(fake_generic_class).MethodSettings(".ctor").MockMethodCalled += (sender, args) =>
            {
                GenericClass<string> inst = (GenericClass<string>) sender;

                // Exception throws by the following line
                ObjectState.SetField(inst, "Foo", (string) args.SentArguments[0]);
            };

            GenericClass<string> test = new GenericClass<string>("testing", null);
        }
    }
}

But I get a exception saying "Field 'Foo' could not be found in type: GenericClass`1, did you mean to mock the property? As a property is a method, use mocking API instead".

asked by Ash (1.6k points)

Please log in or register to answer this question.

...