Friday, June 22, 2007


We are going through our second round of testing some critical business flows in our test lab when it dawned on me how much we use the following NumberGenerator code.  We use it for almost every step of data creation...ok, not that much, but ALOT.  Its kinda goofy, but there you have it.  Its used in many of our scenarios where we are initially seeding data.  e.g. Purchase Order numbers, Work Order numbers, Pallet numbers, or anywhere else we need a sequence of numbers that are formatted with a specific pre/post fix, padded with a specific character to a fixed length and so forth.

using System;
using System.Collections.Generic;
using System.Text;

namespace ARTDC
class NumberGenerator

int _currentNumber = 0;
string _prefix = string.Empty;
string _postfix = string.Empty;
char _padChar = '0';
int _numberLength = 0;
int _startNumber = 0;

/// <summary>
/// Returns a formatted string such as 'CWTEST0000000000000001'
/// </summary>
/// <param name="prefix">Hardcoded prefix to string, e.g. 'CWTEST'</param>
/// <param name="startNumber">Number to start incrementing at. e.g. 1.</param>
/// <param name="numberLength">Total length of the formatted 'number' string. e.g. 20</param>
/// <param name="padChar">The character to pad to length with. e.g. '0'.</param>
public NumberGenerator(string prefix, string postfix, int startNumber, int numberLength, char padChar)

_prefix = prefix;
_startNumber = startNumber;
_numberLength = numberLength;
_padChar = padChar;
_postfix = postfix;

_currentNumber = _startNumber;


/// <summary>
/// Returns a formatted 'number' string on each call
/// </summary>
/// <returns></returns>
public string Next()

string result;
string tempNumber = _currentNumber.ToString();

result = string.Format("{0}{1}{2}", _prefix, tempNumber.PadLeft(_numberLength - _prefix.Length, _padChar), _postfix);


return result;


I'm not making any claims around it...just it was one of those moments where I reflected on the value of this little piece of code.  Of course, anyone could have cranked out the same piece of code a dozen different ways, using different tools, but we did it this way.  Anyway...I'm through reflecting..

How do you generate test data?

1 comment:

  1. Michal10:30 PM

    Uh oh, your "postfix" parameter isn't documented! :)

    GNU's coreutils have the "seq" program for generating sequences:

    % seq --format "CWTEST%020g" 1 10

    (integers between 1 and 10)

    Or to generate for an arbitrary number once, you can do:

    % seq --format "CWTEST%020g" 13 13

    It also has the flexibility of floating point values:

    % seq --format "CWTEST%020.3f" 1 .31 2

    (numbers betweeen 1 and 2 with step size of .31 and three spots after the decimal place)

    This is all a wrapper for the sprintf() call in C.