Home > Blockchain >  Unit Test: random string for TestCase in c#?
Unit Test: random string for TestCase in c#?

Time:10-05

How to set random string in unit Test for TestCase Attribute? How to create a test with random inputs in c#?

    [Test]
    [TestCase("")]
    public async Task TestGet(string inp){....}


        public string CreateRandomString(int size)
         {
           StringBuilder builder = new StringBuilder();
           Random random = new Random();

           char c;
           for (int i = 0; i < size; i  )
           {
            c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble()   
             65)));
            builder.Append(c);
        }
        return builder.ToString();
    }

CodePudding user response:

With NUnit, you can use a TestCaseSource:

[Test]
[TestCaseSource(nameof(CreateRandomStrings))]
public void TestGet(string input)
{
  // your test ...
}

public IEnumerable<string> CreateRandomStrings()
{
  // create 5 random strings
  for (int i = 0; i < 5;   i)
  {
    yield return CreateRandomString(10);
  }
}


private static readonly Random random = new Random();
public string CreateRandomString(int size)
{
   StringBuilder builder = new StringBuilder();

   char c;
   for (int i = 0; i < size; i  )
   {
    c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble()   65)));
    builder.Append(c);
   }
   return builder.ToString();
}

CodePudding user response:

You can use TestCaseSource attribute to do that:

public static string RandomString()
{
    const string alphabet = "abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    int size = 50;
    char[] chars = new char[size];
    for (int i = 0; i < size; i  )
    {
        Random rand = new Random();

        chars[i] = alphabet[rand.Next(alphabet.Length)];
    }

    var a = new string(chars);
    return a;
}

[Test]
[TestCaseSource(nameof(RandomString))]
public void TestGet(string random)
{
    // Do something
}
  • Related