c# - 使用 List<string>、Autofixture 创建测试数据

标签 c# unit-testing autofixture

尝试让这个简单的测试发挥作用:

public class MyClass
{
    public string Text { get; set; }
    public List<string> Comments { get; set; }

}
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var fixture = new Fixture();
        fixture.Customize<string>(c => c.FromSeed(s => s)); //Just return propertyname, no GUID appended
        var test = fixture.Create<MyClass>();

    }
}

但我不断收到错误

The decorated ISpecimenBuilder could not create a specimen based on the request: System.String. This can happen if the request represents an interface or abstract class; if this is the case, register an ISpecimenBuilder that can create specimens based on the request. If this happens in a strongly typed Build<T> expression, try supplying a factory using one of the IFactoryComposer<T> methods.`

如果我删除 Customize线,似乎有效...

不太确定我需要做什么才能使其正常工作

最佳答案

您可以通过自定义 Fixture 实例来创建 string 实例,而无需附加 GUID,如下所示:

public void GuidsAreNotAppendedOnStringValues()
{
    var fixture = new Fixture();
    var expected = string.Empty;
    fixture.Customizations.Add(
        new StringGenerator(() => expected));

    var actual = fixture.Create<MyClass>();

    Assert.Equal(expected, actual.Comments.Aggregate((x, y) => x + y));
}

这样,Text 属性也是 Text,而不是 Texte85e2f6f-c1a3-47c7-baf2-4756c498f523

关于c# - 使用 List<string>、Autofixture 创建测试数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24573629/

相关文章:

C# 和.NET : stackalloc

android - Robolectric - BuildActivity(MyActivity.class).create() 抛出 NullPointerException

unit-testing - 不要模拟域对象规则?

autofixture - 如何使用 AutoFixture 填充方法的返回值

c# - (DLLImport)尝试读取或写入 protected 内存。这通常表明其他内存已损坏

c# - 无法弄清楚为什么我的 If else/Else if 语句不起作用。 C#

c# - IServerSideEvents 的 IOC 注入(inject)

mocking - 此测试是否正确使用了AutoFixture和Moq?

c# - 有没有办法告诉 Autofixture 只设置具有特定属性的属性?

c# - 使用 ASP.NET MVC 中父页面模型的内容填充 PartialView 模型