2

Ultimately I want to have an internal interface with a setter and a public one with a getter. The code that replicates this scenario is roughed below:

    [TestMethod]
    public void TestMethod3()
    {
        var fake1 = A.Fake<IInterface1>(a => a.Implements(typeof(IInterface2)));

        string backingString = null;

        IInterface2 fake2 = (IInterface2)fake1;
        A.CallTo(fake1)
            .Where(a => a.Method.Name.Equals("set_Property"))
            .Invokes((string param) => { backingString = param; });
        A.CallTo(fake1)
            .Where(a => a.Method.Name.Equals("get_Property"))
            .WithReturnType<string>().Returns(backingString); //doesn't work

        A.CallTo(fake2)
            .Where(a => a.Method.Name.Equals("set_Property"))
            .Invokes((string param) => { backingString = param; });
        A.CallTo(fake2)
            .Where(a => a.Method.Name.Equals("get_Property"))
            .WithReturnType<string>().Returns(backingString); //doesn't work

        fake1.Property = "asdf";


        Assert.AreEqual("asdf", fake1.Property); //fails -> fake1.Property is null
        Assert.AreEqual(fake1.Property, fake2.Property); //fails -> fake2.Property is null
    }
}

public interface IInterface1
{
    string Property { get; set; }
}

public interface IInterface2
{
    string Property { get; }
}

I could get as far as using backingString to store the setter, but when setting up the getter it doesn't work as I wanted it to.

I also tried something in the line of A.CallTo(() => fake1.Property).Returns(backingString) to no avail.

Would appreciate assistance of them experts :)

johnildergleidisson
  • 2,087
  • 3
  • 30
  • 50
  • 1
    Can you explain in more details what are you trying to achieve? Are you trying to create a fake that returns a specific value when its property getter is invoked? – Yacoub Massad Sep 09 '15 at 21:55
  • @YacoubMassad The point was to get around [this "issue"|http://stackoverflow.com/questions/32405776/fakeiteasy-problems-with-new-modifier]. Essentially I wanted to have the fake object behave like a real object when implementing two interfaces with a property with the same name. Regardless of its polymorphic shape it should return the same value. – johnildergleidisson Sep 10 '15 at 13:59

1 Answers1

2

When you set up your

A.CallTo(fake1)
    .Where(a => a.Method.Name.Equals("get_Property"))
    .WithReturnType<string>().Returns(backingString);

(and similarly for fake2),

the value of backingString is null, so that's what's returned later on when you access the Property getter.

In order to return the value of backingString at the time the Property getter is called, you want ReturnsLazily.

Make this change in each place and the tests pass:

A.CallTo(fake1)
    .Where(a => a.Method.Name.Equals("get_Property"))
    .WithReturnType<string>().ReturnsLazily(() => backingString);
Blair Conrad
  • 233,004
  • 25
  • 132
  • 111