使用List <string>,Autofixture </string>创建testdata

时间:2014-07-04 11:50:09

标签: 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>();

    }
}

但我一直收到错误

  

装饰的ISpecimenBuilder无法根据请求创建样本:System.String。如果请求表示接口或抽象类,则会发生这种情况;如果是这种情况,请注册可以根据请求创建标本的ISpecimenBuilder。如果在强类型Build<T>表达式中发生这种情况,请尝试使用IFactoryComposer<T>方法之一提供工厂。

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

不太确定我需要做些什么才能让它发挥作用

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

结束,添加我自己的ISpecimenBuilder

public class TextBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as PropertyInfo;
        if (pi == null)
            return new NoSpecimen(request);
        if (pi.PropertyType == typeof(string))
            return pi.Name;
        if (pi.PropertyType == typeof(IList<string>) || pi.PropertyType == typeof(List<string>))
        {
            var tmps = (List<string>)context.Resolve(typeof(List<string>));
            for (var n = 0; n != tmps.Count; ++n)
                tmps[n] = pi.Name + n.ToString(CultureInfo.InvariantCulture);
            return tmps;
        }
        return new NoSpecimen(request);
    }
}