6587

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

Typemock Developers Community Site Updated

Typemock has updated its Developers Community Site with new sections.

Besides the forums, there's a new add-ons page where anyone can share her/his tools or snippets (I guess I'll have to brush up my Typemock Snippets For Visual Studio to add there) and an experts page (guess who's there).

Typemock fan Meet the experts

Typemock Isolator v4.2.4 Released

Typemock released version 4.2.4 of its Isolator mock framework.

You can check out the release notes in The Typemock Insider blog and download it from the Typemock Isolator Download page.

Upcoming Typemock Webcast on March 12

Typemock is having a special Webcast on Wednesday March 12, 16:00 GMT

The live demo will include:

  • The Support of the new .NET 3.5 framework and specifically how to mock LINQ statements.
  • The improved IDE based on using colors to emphasize mocked methods.
  • Seamless integration with  Microsoft’s Visual Studio 2008.

It is also an opportunity to meet Typemock’s development team, ask questions online and share some tips.

.....and one of you can win a Nintendo Wii during in the webcast!

Click here to participate in the Webcast

TypeMock Isolator 4.2 Released

TypeMock has released version 4.2 of its mocking framework: TypeMock Insulator. Check out the release notes.

My four favorite new features in this release are:

Improved mock chaining

(If you want to learn more about chains, read this post from Gil)

Take this class to be tested:

public class TestedClass1
{
    public IDictionary<string, object> Dictionary
    {
        get { throw new NotImplementedException(); }
    }

    public object Method(bool cond)
    {
        if (cond)
        {
            return Dictionary["true"];
        }
        else
        {
            return Dictionary["false"];
        }
    }
}

The following test:

[TestMethod]
[VerifyMocks]
public void TestMethod1()
{
    object trueObject = new object();
    object falseObject = new object();

    TestedClass1 target = RecorderManager.CreateMockedObject<TestedClass1>();

    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
        recorder.DefaultBehavior.CheckArguments();

        recorder.ExpectAndReturn(target.Dictionary["true"], trueObject);
        recorder.FailWhenCalled(target.Dictionary["false"]);
    }

    object value = target.Method(true);
    Assert.AreEqual(trueObject, value);
}

Would simply fail with:

Test method TestProject1.UnitTest1.TestMethod1 threw exception:  TypeMock.VerifyException: 
TypeMock Verification: Method TestProject1.TestedClass1.get_Dictionary() has 1 more expected calls
.

Now, it just passes.

Debugger evaluation doesn't change the test behavior

Now you can debug your code without having to change your tests. You can query mocked values without influencing your tests.

You can do this and still have the test passing:

Debugger Support

The debugger can be run inside a recording block without confusing the test

You can now step into the recording block and debug it without affecting the recording process and the test.

Recording Block

When you step in the debugger into a mocked method, the mocked method will be painted

When you step into a mocked method (or property) I'll see that it's mocked.

Visual Studio Cues

Typemock Insulator Is Typemock Isolator

Yesterday I made a mistake with the name of the next version of TypeMock. The real name is TypeMock Isolator. Whatever the name is, you should try it out.

TypeMock Insulator 4.2 Beta Publicly Available

TypeMock (now called) Insulator 4.2 Beta is publicly available. Check out the release notes.

One of my favorite new features is the improved mock chaining.

Take this class to be tested:

public class TestedClass1
{
    public IDictionary<string, object> Dictionary
    {
        get { throw new NotImplementedException(); }
    }

    public object Method(bool cond)
    {
        if (cond)
        {
            return Dictionary["true"];
        }
        else
        {
            return Dictionary["false"];
        }
    }
}

The following test:

[TestMethod]
[VerifyMocks]
public void TestMethod1()
{
    object trueObject = new object();
    object falseObject = new object();

    TestedClass1 target = RecorderManager.CreateMockedObject<TestedClass1>();

    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
        recorder.DefaultBehavior.CheckArguments();

        recorder.ExpectAndReturn(target.Dictionary["true"], trueObject);
        recorder.FailWhenCalled(target.Dictionary["false"]);
    }

    object value = target.Method(true);
    Assert.AreEqual(trueObject, value);
}

Would simply fail with:

Test method TestProject1.UnitTest1.TestMethod1 threw exception:  TypeMock.VerifyException: 
TypeMock Verification: Method TestProject1.TestedClass1.get_Dictionary() has 1 more expected calls
.

Now, it just passes.

Visual Studio cues are nice too.

TypeMock: How to Make Reflective Mocks More Natural

Like I said before, this as been on the back of my mind for a while.


A while back I introduced a way to get the MethodInfo of a method in a strongly typed way using LINQ, and that's how I'm going to make Reflective Mocks more Natural.


Well, it's as easy as this:

public static class MockExtender
{
public static IParameters ExpectAndReturn<T1, T2, TResult>(this IMockControl mock, Expression<Func<T1, T2, TResult>> expression, object ret, params Type[] genericTypes)
{
return mock.ExpectAndReturn((expression.Body as MethodCallExpression).Method.Name, ret, genericTypes);
}
}

(For now, I'll leave to someone else the implementation of the rest of the overloads)


With this implementation it's possible to handle static classes (a limitation of Fredrik's implementation).


As for private methods, just let Visual Studio (2008, in this sample) and TypeMock do their magic.


So, to test this class:

public static class Class1
{
public static string PublicMethod(string param1, int param2)
{
return PrivateMethod(param2, param1);
}

private static string PrivateMethod(int param2, string param1)
{
throw new NotImplementedException();
}
}


We just write this test:

[TestMethod()]
public void PublicMethodTest()
{
string param1 = "param";
int param2 = 5;
string expected = "return";
string actual;

Mock targetMock = MockManager.Mock(typeof(Class1));

targetMock.ExpectAndReturn((int i, string s) => ClassLibrary1.Class1_Accessor.PrivateMethod(i, s), expected).Args(param2, param1);

actual = Class1.PublicMethod(param1, param2);

Assert.AreEqual(expected, actual);
}


How about this for clean and simple?

TypeMock: Making Reflective Mocks More Natural

I've been thinking about this for a while. Seems like someone beat me to it.

TypeMock Basic Introduction Screencast at Facebook

Roy Osherove done a nice introductory 10 minute screencast that shows some basic features in TypeMock.