3

I'm trying to create a not empty string generator but when running the test I still have empty strings as inputs.

Here is the code I wrote:

    [Test]
    public void MyTest()
    {
        Func<Gen<string>> generateNotEmptyString = () =>
        {
            var gen = Any.OfType<string>()
                         .Where(name => !string.IsNullOrEmpty(name));
            return gen;
        };

        Action<string> assertIdIsNeverEmpty = name =>
        {
                var id = MyService.CreateId(name);
                id.Should().NotBeNullOrEmpty();
        };

        Spec.For(generateNotEmptyString(), assertIdIsNeverEmpty)
            .QuickCheckThrowOnFailure()
    }

I'm using NUnit v. 2.6.2.12296, FsCheck v. 0.9.4.0 and FluentAssertions v. 3.0.90.0.

What if I also want to modify the generator so that it creates not empty strings that match a regular expression?

[EDIT] This is the code I'm using to create strings that contain letters but don't contain special characters:

    private static Gen<NonEmptyString> GenerateValidNames()
    {
        return
            Any.OfType<NonEmptyString>()
                .Where(s =>
                    !s.Get.Contains("\r") &&
                    !s.Get.Contains("\n") &&
                    !s.Get.Contains("\t"))
                .Where(s =>
                {
                    var regEx = new Regex(@"^[A-Za-z]*$");
                    return regEx.Match(s.Get).Success;
                });            
    }
4

1 回答 1

2

也许你有一个错误:)以下对我有用:

    public void MyTest()
    {
        Gen<string> generateNotEmptyString = Any.OfType<string>()
                                                .Where(name => !string.IsNullOrEmpty(name));

        Action<string> assertIdIsNeverEmpty = name =>
        {
                Assert.False(String.IsNullOrEmpty(name));
        };

        Spec.For(generateNotEmptyString, assertIdIsNeverEmpty)
            .QuickCheckThrowOnFailure();
    }

请注意,您不需要生成器周围的额外功能。生成器在幕后已经是一个函数,因此仅创建一个不会执行任何代码(或多或少),就像 IEnumerable 一样。

或者,使用内置的非空字符串生成器:

        Action<NonEmptyString> assertIdIsNeverEmpty = name =>
        {
                Assert.False(String.IsNullOrEmpty(name.Get));
        };

        Spec.For(Any.OfType<NonEmptyString>(), assertIdIsNeverEmpty)
            .QuickCheckThrowOnFailure();

生成与正则表达式匹配的字符串是一个已解决的问题,但并不简单。FsCheck 目前不直接支持它。虽然我认为这会是一个很好的补充!请参阅如何生成与给定正则表达式匹配的随机字符串?

于 2014-07-11T08:11:12.860 回答