簡體   English   中英

使用 C# 中的 FsCheck.Xunit 調整字符串生成器以避免“\0”

[英]Adjust string generator to avoid “\0” with FsCheck.Xunit in C#

在使用字符串輸入創建 FsCheck.Xunit 單元測試時,我經常遇到包含“\0”的字符串,我相信這些字符串會輸入 C 庫並導致字符串截斷。 如果您運行下面的測試,您會發現 FsCheck 經常創建包含“\0”的字符串。

調整字符串生成器以避免包含“\0”的字符串的最簡單方法是什么? 我需要在多個測試中使用這種行為,並且正在使用 .NET Core。

BR,馬克

public class NewTests
{

    [Property(Verbose = true)]
    public Property Test1(string myString)
    {
        return (!myString.Contains("\0")).ToProperty();
    }

}

最簡單的方法是在測試中將其過濾掉,例如使用輔助方法。 但是請注意,字符串本身也可以是 null。

如果您想要可以是null但不包含null字符的字符串:

[Property]
public bool TestIt(StringNoNulls s)
{
    return s.Item == null || !s.Item.Contains("\0");
}

如果你想要非空字符串:

[Property]
public bool TestIt(NonNull<string> s)
{
    return s != null;
}

如果你想要兩者,我沒有開箱即用的東西,但是:你可以做類似的事情:

public class CustomArbs
{
    public static Arbitrary<string> ReallyNoNullsAnywhere()
    {
        return Arb.Default.String().Filter(s => s != null && !s.Contains("\0"));
    }
}

[Property(Arbitrary = new[] { typeof(CustomArbs) })]
public bool TestIt(string s)
{
    return s != null && !s.Contains("\0");
}

還有PropertiesAttribute ,您可以將其放在 class 上,以覆蓋該 class 中所有屬性上特定類型集的所有 Arbitrary 實例,因此您不必在每個測試方法上添加 Arbitrary 參數。

我最終經常使用的一種模式不是覆蓋Arbitrary<string>實例本身,而是制作一個包裝器類型,因此在簽名中我得到的是什么類型的字符串變得很清楚:

public class AntiNullString
{
    public string Get { get; }

    public AntiNullString(string s)
    {
        Get = s;
    }
}

public class CustomArbs
{
    public static Arbitrary<AntiNullString> ReallyNoNullsAnywhere()
    {
        return Arb.Default.String()
            .Filter(s => s != null && !s.Contains("\0"))
            .Convert(s => new AntiNullString(s), ans => ans.Get);
    }
}

[Property(Arbitrary = new[] { typeof(CustomArbs) })]
public bool TestIt(AntiNullString s)
{
    return s.Get != null && !s.Get.Contains("\0");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM