【问题标题】:AutoFixture Create An Instance from An Interface IssueAutoFixture 从接口问题创建实例
【发布时间】:2020-10-23 12:59:05
【问题描述】:

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

这是我的例子:

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

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

具体类是自动生成的,它的属性如下:

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

如何像具体类一样从接口创建实例?

【问题讨论】:

标签: c# unit-testing asp.net-core mocking autofixture


【解决方案1】:

同意 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 是要考虑的选项。

【讨论】:

  • 我是否必须编写一个从我的接口派生的类?我不想这样做。
  • 然后使用 AutoMoq 或 AutoNsubstitute
  • 谢谢,我之前错过了自动起订量。 new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true }) 这个代码块解决了我的问题。特别是ConfigureMember = true.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 2016-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多