How to pass random string in input field using selenium C#

In this example, I am going to explain to you how to add a random string in the input field using selenium C#. During the automation, we face this problem regularly. So how can pass a new string in an input field in selenium using c#? Let’s understand the problem first.

Scenario example

For example, I am automating a registration form where I need to pass a “UserName”. Which accepts only a unique value. If you pass the same value then it will show a message “Record already exists”. In this case, your test case is executed only once. When you run it second time you will face the issue “Record already exists”. So, pass random string in input field using selenium C#.

Random string in input field using selenium C#

random string in input field using selenium C#

Solution

We can create a random string for every execution. Like here I create a custom method to Generate a random value in every execution. It will take two parameters 1) Length of the spring 2) true/false to covert this in Upper and lower case and Return a random string on every calling request.

Create Random string in C#

// Generate a random string with a given size

public static string RandomString(int size, bool lowerCase)

{

StringBuilder builder = new StringBuilder();

Random random = new Random();

char ch;

for (int i = 0; i < size; i++)

{

ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));

builder.Append(ch);

}

if (lowerCase)

return builder.ToString().ToLower();

return builder.ToString();

}

When you call this method like “RandomString(4, true)” it will return a string of size 4 in lower case and if you call this like “RandomString(5, False)” it will return a string of size 5 in uppercase letter. By this, you can create only String value. Now Let’s in how can create random value of integer type.

Create Random Number in C#

This method will take two input parameter 1) for the starting number 2) for the last number and it will return an int value between the start number and end number.

public static int RandomInt(int from, int to)

{

Random random = new Random();

int n = random.Next(from, to);

return n;

}

When you call this RandomInt(100,999) then it will return all the random number in 3 digit means between 100 to 999.

Create Random Number of double type in C#

public static double RandomInt()

{

Random random = new Random();

double n = random.NextDouble();

Console.WriteLine(n);

return n;

}

Here, We are using NextDouble() it will return a random number of double type between 0.0 to 1.0. So when you call RandomInt() it will return a random number of double type.

These all are the most common requirement to pass random string in input field using selenium C#. We can use according to the requirement. Find more web automation trick using selenium and C#.

Add a Comment

Your email address will not be published. Required fields are marked *

4 × one =