AutoFixture 从接口问题创建实例

AutoFixture Create An Instance from An Interface Issue

我的问题是,无法从界面创建自动生成的实例。

这是我的例子:

public class SomeClass {
    public string TestName { get; set; }
}

// And then I call like this
var obj = new Fixture().Create<SomeClass>();

混凝土 class 是自动生成的,它的属性如下:

Console.WriteLine(obj.TestName);
// Output: TestNameb7c3f872-9286-419f-bb0a-c4b0194b6bc8

但是我的界面如下:

public interface ISomeInterface 
{
    string TestName { get; set; }
}

// And  then I call like this
var obj = new Fixture().Create<ISomeInterface >();

已生成但未设置其属性。

Console.WriteLine(obj.TestName);
// Output: null

如何从具体的界面创建实例 class?

同意 Mathew Watson 的评论,这个问题可能已经在提到的问题中得到了回答。

只是想分享我的版本,它与 2012 年的答案略有不同;)

public interface ISomeInterface
{
    string TestName { get; set; }
}

public class SomeClass : ISomeInterface
{
    public string TestName { get; set; }
}

public class Test
{
    [Fact]
    public void Do()
    {
        var fixture = new Fixture();
        fixture.Customize<ISomeInterface>(x => x.FromFactory(() => new SomeClass()));
        var result = fixture.Create<ISomeInterface>();
        Console.Out.WriteLine("result = {0}", result.TestName);
        // output:
        // result = TestName2c7e6902-d959-46ce-a79f-bf933bcb5b7f
    }
}

当然,AutoMoq 或 AutoNSubstitute 是要考虑的选项。