最终,我希望有一个带有setter的内部接口和一个带有getter的公共接口。复制此方案的代码如下:
[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; }
}
我可以使用
backingString
来存储setter,但设置getter时并不能达到我想要的效果。我也尝试了
A.CallTo(() => fake1.Property).Returns(backingString)
行中的任何操作,但无济于事。希望得到他们专家的帮助:)
最佳答案
当您设置好
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().Returns(backingString);
(对于
fake2
同样),backingString
的值是null
,因此这是稍后访问Property
getter时返回的内容。为了在调用
backingString
getter时返回Property
的值,您需要ReturnsLazily。在每个地方进行更改,然后测试通过:
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().ReturnsLazily(() => backingString);