Using Random Values For Unit Testing

When writing my unit tests I don’t like to use hard coded fixed values because I either end up using the same values or, because of that, tests may succeed by coincidence.

Over time, I have developed an helper class to generate random values for testing.

namespace PauloMorgado.VisualStudio.TestTools.UnitTesting
    public static class RandomGenerator
        public static bool Boolean();
        public static string String();
        public static string String(string prefix);
        public static short Int8();
        public static short Int8(short maxValue);
        public static short Int8(short minValue, short maxValue);
        public static short Int16();
        public static short Int16(short maxValue);
        public static short Int16(short minValue, short maxValue);
        public static int Int32();
        public static int Int32(int maxValue);
        public static int Int32(int minValue, int maxValue);
        public static TEnum Enum<TEnum>();
        public static TEnum EnumFlagsWith<TEnum>(TEnum flagsToAdd);
        public static TEnum EnumFlagsWithout<TEnum>(TEnum flagsToRemove);
        public static TEnum Enum<TEnum>(int maxValue);
        public static TEnum Enum<TEnum>(int minValue, int maxValue);
        public static System.Guid Guid();

This is something that I would like to find on mock frameworks (like Typemock Isolator, Rhino.Mocks or MoQ).

It’s still a work in progress, but if you want to try it, it’s on my MSDN Code Gallery: Random Generator For Unit Testing

2 Responses to Using Random Values For Unit Testing

  • Simon says:


    Hope you’re well!

    Interesting post – I totally agree that a wider range of test values significantly increases the benefit of unit tests, but I’d generally want every instance of the test I run to be repeatable on *every* run. So I’d be inclined to use the data source functionality in VSTS Unit Tests, for example. In other words, decide my random (or hand crafted) range of values at design time, not test execution time.

    How would you deal with diagnosing a problem in a failed test? Do you find you need to explicitly log more information (e.g. all the arguments to your method) in the event of a failure? Or have I missed something obvious?!


  • paulo says:

    Hi Simon. I’m fine, and you?

    I hope this answers your question: