在AutoFixture ISpecimenBuilder中使用RegEx时,为什么我总是得到相同的值?

时间:2015-08-31 20:39:21

标签: c# regex unit-testing autofixture

我的构建器设置为处理参数或属性。这可能会在未来发生变化,但现在这就是我在构建器中所拥有的:

public class UserNameBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
       var propertyInfo = request as PropertyInfo;
        if (propertyInfo != null && propertyInfo.Name == "UserName" && propertyInfo.PropertyType == typeof(string))
        {
            return GetUserName();
        }

        var parameterInfo = request as ParameterInfo;
        if (parameterInfo != null && parameterInfo.Name == "userName" && parameterInfo.ParameterType == typeof(string))
        {
            return GetUserName();
        }

        return new NoSpecimen(request);
    }

    static object GetUserName()
    {
        var fixture = new Fixture();
        return new SpecimenContext(fixture).Resolve(new RegularExpressionRequest(@"^[a-zA-Z0-9_.]{6,30}$"));
    }
}

我的UserName对象是ValueType对象,如下所示:

public class UserName : SemanticType<string>
{
    private static readonly Regex ValidPattern = new Regex(@"^[a-zA-Z0-9_.]{6,30}$");

    public UserName(string userName) : base(IsValid, userName)
    {
        Guard.NotNull(() => userName, userName);
        Guard.IsValid(() => userName, userName, IsValid, "Invalid username");
    }

    public static bool IsValid(string candidate)
    {
        return ValidPattern.IsMatch(candidate);
    }

    public static bool TryParse(string candidate, out UserName userName)
    {
        userName = null;

        try
        {
            userName = new UserName(candidate);
            return true;
        }
        catch (ArgumentException ex)
        {
            return false;
        }
    }
}

UserName类继承自SemanticType,这是一个为我的值类型提供基础的项目。

每当我使用AutoFixture时如下:

var fixture = new Fixture();
fixture.Customizations.Add(new UserNameBuilder());

var userName = fixture.Create<UserName>();

我总是得到价值“......”我以为每次都会得到不同的价值。我看到了预期的行为吗?

1 个答案:

答案 0 :(得分:3)

如果可能,favor negated character classes instead of the dot,并尝试use the dot sparingly

^([a-zA-Z0-9]|[._](?![.])){6,30}$

Regular expression visualization

上述正则表达式匹配的文本也会被提供的原始文本匹配,例如: nik_s.bax_vanis

它也使AutoFixture生成不同的文本(原谅我的F#):

// PM> Install-Package Unquote
// PM> Install-Package AutoFixture
// PM> Install-Package FsCheck.Xunit

open FsCheck
open FsCheck.Xunit
open Ploeh.AutoFixture
open Ploeh.AutoFixture.Kernel
open Swensen.Unquote

[<Property>]
let ``Generated strings from RegEx are not all the same`` (PositiveInt count) =
    let fixture = new Fixture()
    let context = new SpecimenContext(fixture)

    let results = seq {
        for i in 1 .. count do
            yield context.Resolve(
                new RegularExpressionRequest("^([a-zA-Z0-9]|[._](?![.])){6,30}$")) }

    let threshold = count / 10
    results |> Seq.distinct |> Seq.length >! threshold

原始的正则表达式很好。 - 它是引擎,尽可能多次重复dot

^[a-zA-Z0-9_.]{6,30}$

Regular expression visualization