2017-10-19 82 views
2

我正在嘗試解決鑽石kata以瞭解如何使用fscheck庫編寫基於屬性的測試。我想用C#編寫測試,我正在使用Visual Studio 2017.C#,xunit,fscheck,使用自定義生成器或受約束的隨機字符串編寫基於簡單屬性的測試

我想編寫一個基於屬性的測試,它不會生成任何隨機字符作爲輸入,而只是字母。我不知道如何編寫生成器fscheck需要執行此操作以及在哪個文件中放置代碼?

我到處搜索和閱讀文檔,但有麻煩(部分原因是我不能很好地將F#翻譯成C#)。

[Property]如何將輸入數據限制爲僅字母?

如果有更好的方法,請讓我知道。

[編輯:]

我編輯我的代碼的例子,其現在包含由庫爾特Schelfthout一個工作溶液。



測試

using DiamondKata; 
using FsCheck; 
using FsCheck.Xunit; 
using Xunit; 

namespace DiamondKataTests 
{ 
    public static class Arbitraries 
    { 
     private static readonly string upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
     private static readonly string lowerAlphabet = ""; //upperAlphabet.ToLower(); 
     private static readonly char[] wholeAlphabet = (lowerAlphabet + upperAlphabet).ToCharArray(); 
     public static Arbitrary<char> LetterGenerator() 
     { 
      return Gen.Elements(wholeAlphabet).ToArbitrary(); 
     } 
    } 

    public class DiamondKataTests 
    { 
     // THIS WORKS and is apparently the preferred way of doing things 
     // also see here: https://stackoverflow.com/questions/32811322/fscheck-in-c-generate-a-list-of-two-dimension-arrays-with-the-same-shape 
     [Property()] 
     public Property shouldReturnStringAssumesValidCharWasProvided() 
     { 
      return Prop.ForAll(Arbitraries.LetterGenerator(), letter => 

       // test here 
       Assert.NotNull(Diamond.Create(letter)) 
      ); 
     } 

     // Second solution ... 
     // Error here: Arbitraries is a type not valid in the given context 
     [Property(Arbitrary = new[] { typeof<Arbitraries> })] 
     public void testThatAssumesValidCharWasProvided(char lettersOnlyHERE) 
     { 
      // ? 
     } 
    } 
} 

類來測試

namespace DiamondKata 
{ 
    public class Diamond 
    { 
     public static string Create(char turningPointCharacter) 
     { 
      return ""; 
     } 
    } 
} 

回答

0

你不能把限制在ttributes,可以傳遞給屬性的類型僅限於這樣做。

您有幾個選項。您可以爲char定義一個自定義Arbitrary實例,即實現Arbitrary<char>並配置該屬性以使用該實例。

public static class Arbitraries 
{ 
    public static Arbitrary<char> LetterGenerator() 
    { 
     return Gen.Elements(wholeAlphabet).ToArbitrary(); 
    } 
} 

public class DiamondKataTestClass1 
{ 
    [Property(Arbitrary=new[] { typeof<Arbitraries> })] 
    public void testThatAssumesValidCharWasProvided(char lettersOnlyHERE) 
    { 
     // ? 
    } 
} 

您還可以使用更靈活的API定製生成在線:

public class DiamondKataTestClass1 
{ 
    [Property()] 
    public Property testThatAssumesValidCharWasProvided() 
    { 
     Prop.ForAll(Arbitraries.LetterGenerator()) (letter => 
     // test here 
     ) 
    } 
} 
+0

非常感謝您的回覆,很遺憾,您的解決方案給我的錯誤。我編輯了上面的帖子,其中包括您的代碼和評論,我得到的錯誤...謝謝! – Shakka

+0

找到了我自己的一個錯誤的修復方法,你的語法稍微偏離了,我冒昧地修改了你的解決方案,再次感謝你! – Shakka

相關問題