FakeItEasy深嵌套类型伪造

Aki*_*lov 5 unit-testing mocking fakeiteasy

我有一个复杂的对象,我试图伪造.

interface IContext
{
    User User { get; }
}

A.CallTo(
    () => _fakeContext.User.Subscription.Attributes)
    .Returns(new List<Attribute>());
Run Code Online (Sandbox Code Playgroud)

但我得到了下一个例外:

The current proxy generator can not intercept the specified method for the following reasons: - Non virtual methods can not be intercepted

所有嵌套类型都是属性,它们是具有get; set;属性修饰符的简单贫血类型.当我调查调试器时,他们都是假的.

有没有办法设置的最后一个属性,避免设置以前的所有属性

k.m*_*k.m 3

如果你的对象足够贫乏,你可能想尝试一下AutoFixture

var fake = A.Fake<>();
var fixture = new Fixture();
// If it's possible [1], AutoFixture will generate entire object graph
var user = fixture.CreateAnonymous<User>();
// Since data will be random [2], you can overwrite properties as you like
user.User.Subscription.Attributes = new List<Attributes>();
A.CallTo(() => fake.User).Returns(user);
Run Code Online (Sandbox Code Playgroud)
  1. 为了使其工作,您的自定义对象需要具有公共构造函数,并且最好避免使用接口(但这可以通过自动模拟扩展来缓解,例如 AutoFakeItEasy)。
  2. .Build方法提供流畅的API来定制对象自动生成,因此可以控制随机性