4

我试图找到最流畅的方式来断言某个字符串是有效的 Guid。

iterTags.GUID是一个string

我的第一次尝试以错误告终,因为string没有实现Guid. 好的,我看到它来了,因为它是在黑暗中拍摄的

iterTags.GUID.Should().BeAssignableTo<Guid>();

所以我想出了这个可行的解决方案,但它并不流利

Guid parsedGuid;
if (!Guid.TryParseExact(iterTags.GUID, "D", out parsedGuid))
    Assert.Fail("iterTags.GUID: '{0}' is not a valid guid");

阅读文档我发现没有更好的断言方法。

我的问题:是否有一种流畅方式来断言字符串是有效的Guid

也许,像...

iterTags.GUID.Should().BeParsedAs<Guid>()
4

3 回答 3

3
Guid parsedGuid;
Guid.TryParseExact(iterTags.GUID, "D", out parsedGuid).Should.BeTrue("because {0} is a valid Guid string representation", iterTags.GUID);

或者

new Action(() => new Guid(iterTags.GUID)).ShouldNotThrow("because {0} is a valid Guid string representation", iterTags.GUID);
于 2014-01-23T12:50:53.803 回答
2

您还可以not be empty对 GUID 使用检查,这样您就可以使用FluentAssertions 的空检查:

Guid.TryParse(iterTags.GUID, out var parsedIterTagsGUID)
parsedIterTagsGUID.Should().NotBeEmpty();

或作为扩展:

    public static AndConstraint<FluentAssertions.Primitives.GuidAssertions> ShouldBeGuid(this object value, string because = "", params object[] becauseArgs)
    {
        Guid.TryParse(value?.ToString(), out var guid);
        return guid.Should().NotBeEmpty(because, becauseArgs);
    }

通过扩展其他类似的东西,上面可以做得更好:

    public static AndConstraint<GuidAssertions> BeGuid(this StringAssertions value, string because = "", params object[] becauseArgs)
    {
        Guid.TryParse(value.Subject, out var guid);
        return guid.Should().NotBeEmpty(because, becauseArgs);
    }

    public static AndConstraint<GuidAssertions> BeGuid(this ObjectAssertions value, string because = "", params object[] becauseArgs)
    {
        return (value.Subject as Guid?).Should().NotBeNull().And.NotBeEmpty(because, becauseArgs);
    }

或者通过在以下位置提出拉取请求甚至更好:https ://github.com/fluentassertions/fluentassertions

于 2019-03-25T10:43:11.307 回答
1

受Nick N的回答启发,这就是我最终的结果。

主要区别在于失败消息更清楚地表明字符串不是 GUID,其中NotBeEmpty条件将返回一条消息,说明输入为空。

public static class CustomAssertions
{
    public static AndConstraint<StringAssertions> BeGuid(this StringAssertions assertions, string because = "", params object[] becauseArgs)
    {
        var isGuid = Guid.TryParse(assertions.Subject, out _);

        Execute.Assertion
           .ForCondition(isGuid)
           .BecauseOf(because, becauseArgs)
           .FailWith("Expected a GUID converted to a string{reason}, but found {0}.", assertions.Subject);

        return new AndConstraint<StringAssertions>(assertions);
    }
}
于 2021-08-05T12:20:48.330 回答