I need to generate random string for my automated tests. I use the following Chinese custom class to do it.
public class UniqueIdGenerator
{
static public string GenerateUniqueId(int idLength) // generates uniqueID for all fields (0-175 characters)
{
string uniqueID = "";
string initialID = Guid.NewGuid().ToString().Remove(35);
if (idLength <= 35)
{
uniqueID = Guid.NewGuid().ToString().Remove(idLength);
}
if (idLength > 35 & idLength <= 70)
{
uniqueID = initialID + Guid.NewGuid().ToString().Remove(idLength - 35);
}
if (idLength > 70 & idLength <= 105)
{
uniqueID = initialID + initialID + Guid.NewGuid().ToString().Remove(idLength - 70);
}
if (idLength > 105 & idLength <= 140)
{
uniqueID = initialID + initialID + initialID + Guid.NewGuid().ToString().Remove(idLength - 105);
}
if (idLength > 140 & idLength <= 175)
{
uniqueID = initialID + initialID + initialID + initialID + Guid.NewGuid().ToString().Remove(idLength - 140);
}
return uniqueID;
}
How can I simplify it to use for any natural number?
Try the following:
If all you require is a method capable of generating garbage for testing purposes, then perhaps the following would be more suitable:
As an aside, when randomising values for tests, I prefer to still give my properties descriptive names as I find that the fail messages are generally far more helpful. I use an extension method for this purpose:
Which is the useable in my tests like so:
This may not be applicable in this case, since a string of a given length is required, however it does save a bit of time if/when a test fails.