Fluent Reflection-Based Assertions

An entry about tdd | c# 3.0 Publication date 10. March 2009 11:57

Earlier this year, I shared my set of fluent assertion extension methods for xUnit. Here's a neat update which comes in handy whenever you´re doing assertions on things like anonymous objects – for example the data of a JsonResult from an ASP.NET MVC controller action:

return Json(new { status = "ok"})

Aside: You may balk at this and say we really should have a DTO instead of using anonymous object notation here – and you may be right. But lets disregard that for the rest of this post… :)

Normally, to write a test which verifies that the JsonResult's Data property indeed contains a status property with the value “ok”, we would need to crack it open with reflection:

[Observation]

public void Status_is_ok()

{

    var json = (JsonResult) _result;

 

    PropertyInfo statusProperty = json.Data.GetType().GetProperty("status");

 

    Assert.NotNull(statusProperty);

    statusProperty.GetValue(json.Data, null).ShouldBeEqualTo("ok");

}

That looks pretty ugly and unreadable, I think. So I've packed the ugliness away into a new helper method for my fluent assertion library, allowing me to write the above much more readably:

[Observation]

public void Status_is_ok()

{

    var json = (JsonResult) _result;

 

    json.Data.ShouldHaveProperty("status")

                      .Value

                      .ShouldBeOfType<string>()

                      .ShouldBeEqualTo("ok");

}

Notice also that I've now made it possible to chain assertions together, since the Should methods now return the object being asserted on.

You can download the updated assertion extension methods here

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Fluent, Ubiquitous Assertions with xUnit

An entry about tdd | c# 3.0 Publication date 28. January 2009 13:03

With most testing frameworks, you write assertions like this:

var item = new object();

var list = new List<object> {item};

 

Assert.Equal(1, list.Count);

NUnit introduced a constraint-based assertion model a while back, which lets you write the above assertion in a more fluent manner:

Assert.That(list.Count, Is.EqualTo(1));

While this syntax certainly makes for more naturally readable assertions (“assert that List.Count is equal to 1”), it is quite verbose, awkward and has a less discoverable API (you have to know about all the IConstraints available).

With the extension method feature in C# 3.0, I’ve seen several experienced TDDers begin to use their own custom fluent assertion interfaces, resulting in syntax like this:

list.Count.ShouldBeEqualTo(1);

I’ve been meaning to write a set of extension methods myself to use with xUnit, and I’ve finally found the time to do so:

public static class AssertionHelpers
{
    /// <summary>
    /// Verifies that the string contains a given substring, using the current culture
    /// </summary>
    /// <param name="actualString"></param>
    /// <param name="expectedSubstring">The sub-string expected to be in the string</param>
    public static void ShouldContain(this string actualString, string expectedSubstring)
    {
        Assert.Contains(expectedSubstring, actualString);
    }

    /// <summary>
    /// Verifies that the string contains a given substring, using the given comparison type
    /// </summary>
    /// <param name="actualString"></param>
    /// <param name="expectedSubstring">The sub-string expected to be in the string</param>
    /// <param name="comparisonType">The type of string comparison to perform</param>
    public static void ShouldContain(this string actualString, string expectedSubstring, StringComparison comparisonType)
    {
        Assert.Contains(expectedSubstring, actualString, comparisonType);
    }

    /// <summary>
    /// Verifies that the collection contains a given object
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="collection"></param>
    /// <param name="expected">The object expected to be in the collection</param>
    public static void ShouldContain<T>(this IEnumerable<T> collection, T expected)
    {
        Assert.Contains(expected, collection);
    }

    /// <summary>
    /// Verifies that the collection contains a given object, using the given comparer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="collection"></param>
    /// <param name="expected">The object expected to be in the collection</param>
    /// <param name="comparer">The comparer to use</param>
    public static void ShouldContain<T>(this IEnumerable<T> collection, T expected, IComparer<T> comparer)
    {
        Assert.Contains(expected, collection, comparer);
    }

    /// <summary>
    /// Verifies that the string does not contain a given substring, using the current culture
    /// </summary>
    /// <param name="actualString"></param>
    /// <param name="expectedSubstring"></param>
    public static void ShouldNotContain(this string actualString, string expectedSubstring)
    {
        Assert.DoesNotContain(expectedSubstring, actualString);
    }

    /// <summary>
    /// Verifies that the string does not contain a given substring, using the given comparison type
    /// </summary>
    /// <param name="actualString"></param>
    /// <param name="expectedSubstring"></param>
    /// <param name="comparisonType"></param>
    public static void ShouldNotContain(this string actualString, string expectedSubstring, StringComparison comparisonType)
    {
        Assert.DoesNotContain(expectedSubstring, actualString, comparisonType);
    }

    /// <summary>
    /// Verifies that the collection does not contain a given object
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="collection"></param>
    /// <param name="expected"></param>
    public static void ShouldNotContain<T>(this IEnumerable<T> collection, T expected)
    {
        Assert.DoesNotContain(expected, collection);
    }

    /// <summary>
    /// Verifies that the collection does not contain a given object, using the given comparer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="collection"></param>
    /// <param name="expected"></param>
    /// <param name="comparer"></param>
    public static void ShouldNotContain<T>(this IEnumerable<T> collection, T expected, IComparer<T> comparer)
    {
        Assert.DoesNotContain(expected, collection, comparer);
    }

    /// <summary>
    /// Verifies that the collection is empty
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="collection"></param>
    public static void ShouldBeEmpty<T>(this IEnumerable<T> collection)
    {
        Assert.Empty(collection);
    }

    /// <summary>
    /// Verifies that the objects is equal to the given object, using a default comparer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="actual"></param>
    /// <param name="expected"></param>
    public static void ShouldBeEqualTo<T>(this T actual, T expected)
    {
        Assert.Equal(actual, expected);
    }

    /// <summary>
    /// Verifies that the object is equal to the given object, using a custom comparer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="actual"></param>
    /// <param name="expected"></param>
    /// <param name="comparer"></param>
    public static void ShouldBeEqualTo<T>(this T actual, T expected, IComparer<T> comparer)
    {
        Assert.Equal(actual, expected, comparer);
    }

    /// <summary>
    /// Verifies that the condition is false
    /// </summary>
    /// <param name="condition"></param>
    public static void ShouldBeFalse(this bool condition)
    {
        Assert.False(condition);
    }

    /// <summary>
    /// Verifies that the object is in within a given range
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="actual"></param>
    /// <param name="low">The inclusive low value</param>
    /// <param name="high">The inclusive high value</param>
    public static void ShouldBeInRange<T>(this T actual, T low, T high)
    {
        Assert.InRange(actual, low, high);
    }

    /// <summary>
    /// Verifies that the object is within a given range, using a custom comparer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="actual"></param>
    /// <param name="low">The inclusive low value</param>
    /// <param name="high">The inclusive high value</param>
    /// <param name="comparer">The custom comparer to use</param>
    public static void ShouldBeInRange<T>(this T actual, T low, T high, IComparer<T> comparer)
    {
        Assert.InRange(actual, low, high, comparer);
    }

    /// <summary>
    /// Verifies that the object is assignable from the given type
    /// </summary>
    /// <param name="object"></param>
    /// <param name="expectedType">The type the object should be</param>
    public static void ShouldBeAssignableFromType(this object @object, Type expectedType)
    {
        Assert.IsAssignableFrom(expectedType, @object);
    }

    /// <summary>
    /// Verifies that the object is not of the given type
    /// </summary>
    /// <param name="object"></param>
    /// <param name="expectedType">The type the object should not be</param>
    public static void ShouldNotBeOfType(this object @object, Type expectedType)
    {
        Assert.IsNotType(expectedType, @object);
    }

    /// <summary>
    /// Verifies that the object is of the given type
    /// </summary>
    /// <param name="object"></param>
    /// <param name="expectedType">The type the object should be</param>
    public static void ShouldBeOfType(this object @object, Type expectedType)
    {
        Assert.IsType(expectedType, @object);
    }

    /// <summary>
    /// Verifies that the collection is not empty
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="collection"></param>
    public static void ShouldNotBeEmpty<T>(this IEnumerable<T> collection)
    {
        Assert.NotEmpty(collection);
    }

    /// <summary>
    /// Verifies that the object is not equal to a given object, using a default comparer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="actual"></param>
    /// <param name="expected"></param>
    public static void ShouldNotBeEqualTo<T>(this T actual, T expected)
    {
        Assert.NotEqual(expected, actual);
    }

    /// <summary>
    /// Verifies that the object is not equal to a given object, using a custom comparer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="actual"></param>
    /// <param name="expected"></param>
    /// <param name="comparer"></param>
    public static void ShouldNotBeEqualTo<T>(this T actual, T expected, IComparer<T> comparer)
    {
        Assert.NotEqual(expected, actual, comparer);
    }

    /// <summary>
    /// Verifies that the object is not in the given range
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="actual"></param>
    /// <param name="low">The inclusive low value</param>
    /// <param name="high">The inclusive high value</param>
    public static void ShouldNotBeInRange<T>(this T actual, T low, T high)
    {
        Assert.NotInRange(actual, low, high);
    }

    /// <summary>
    /// Verifies that the object is not in the given range, using a custom comparer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="actual"></param>
    /// <param name="low">The inclusive low value</param>
    /// <param name="high">The inclusive high value</param>
    /// <param name="comparer">The custom comparer</param>
    public static void ShouldNotBeInRange<T>(this T actual, T low, T high, IComparer<T> comparer)
    {
        Assert.NotInRange(actual, low, high, comparer);
    }

    /// <summary>
    /// Verifies that the object is not null
    /// </summary>
    /// <param name="object"></param>
    public static void ShouldNotBeNull(object @object)
    {
        Assert.NotNull(@object);
    }

    /// <summary>
    /// Verifies that the object is not the same as the given object
    /// </summary>
    /// <param name="actual"></param>
    /// <param name="expected"></param>
    public static void ShouldNotBeSameAs(this object actual, object expected)
    {
        Assert.NotSame(expected, actual);
    }

    /// <summary>
    /// Verifies that the object is null
    /// </summary>
    /// <param name="object"></param>
    public static void ShouldBeNull(this object @object)
    {
        Assert.Null(@object);
    }

    /// <summary>
    /// Verifies that the object is the same as the given object
    /// </summary>
    /// <param name="actual"></param>
    /// <param name="expected"></param>
    public static void ShouldBeSameAs(this object actual, object expected)
    {
        Assert.Same(expected, actual);
    }

    /// <summary>
    /// Verifies that the condition is true
    /// </summary>
    /// <param name="condition"></param>
    public static void ShouldBeTrue(this bool condition)
    {
        Assert.True(condition);
    }

    /// <summary>
    /// Verifies that the delegate throws the given exception
    /// </summary>
    /// <typeparam name="EXCEPTION"></typeparam>
    /// <param name="action"></param>
    public static void ShouldThrow<EXCEPTION>(this Action action) 
        where EXCEPTION : Exception
    {
        Assert.Throws<EXCEPTION>(new Assert.ThrowsDelegate(action));
    }

    /// <summary>
    /// Verifies that the delegate does not throw any exceptions
    /// </summary>
    /// <param name="action"></param>
    public static void ShouldNotThrow(this Action action)
    {
        Assert.DoesNotThrow(new Assert.ThrowsDelegate(action));
    }
}

/// <summary>
/// Static gateway for building actions fluently
/// </summary>
public static class The
{
    public static Action Action(Action action)
    {
        return action;
    }
}
}

So far, I’ve created extension methods which wrap all of xUnits Assert methods, but I can certainly imagine other more (domain) specific Should* methods which would be helpful to have as well. Not everybody agrees, though.

Ubiquitous Assertion Syntax

The step from here towards an ubiquitous assertion syntax, as described by Jay Fields, is to create a set of complementary extension methods for behavior based assertions (mock expectations). This would have to involve some lambda trickery, perhaps similar to the ShouldThrow trick I picked up from JP’s blog. More on that later, perhaps.

Currently rated 5.0 by 5 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

A Set of Useful Extension Methods for DateTime

An entry about c# 3.0 Publication date 18. March 2008 19:10

I was just reading Rich Strahl's post today on formatting dates in JavaScript, in which he mentions that the .NET framework has a fairly rich API for working with dates. Compared to JavaScript, he's definitively right - but that doesn't mean that the DateTime API is anything near perfect. Disregarding all the minute detail problems regarding time zones and such, or the fact that we're forced to deal with date AND time together and no separating the two, there are some things that are just plain cumbersome and tedious to get done with it. But lo and behold, with the new extensions method feature in C# 3.0 we can do something about that - so in this post I'd like to present 11 time-saving (oh, the pun!) extensions for the DateTime class.

The Extentions

First()
This method returns a DateTime representing the first day of the month represented by the instance it is called on. For example:

DateTime firstOfMarch = DateTime.Now.First();

 

First(DayOfWeek dayOfWeek)
This method returns the first occurrence of the specified day in the month represented by the instance it is called on. For example, the first Monday of this month was the 3rd of March:

DateTime thirdOfMarch = DateTime.Now.First(DayOfWeek.Monday);

 

Last()
This method returns a DateTime representing the last day of the month represented by the instance it is called on. For example:

DateTime lastDayOfMarch = DateTime.Now.Last();

 

Last(DayOfWeek dayOfWeek)
This method returns a DateTime representing the last occurence of the specified day in the month represented by the instance it is called on. For example, the last Tuesday of this month will be the 25th of March:

DateTime lastTuesdayOfMarch = DateTime.Now.Last(DayOfWeek.Tuesday);

 

Midnight()
This method returns a DateTime representing midnight on the day represented by the instance it is called on:

DateTime midnightToday = DateTime.Now.Midnight();

 

Noon()
This method returns a DateTime representing noon on the day represented by the instance it is called on:

DateTime noonToday = DateTime.Now.Noon();

 

Next(DayOfWeek dayOfWeek)
This method returns the first date falling on the specified day following the one represented by the instance it is called on. For example, to get a DateTime representing next monday:

DateTime nextMonday = DateTime.Now.Next(DayOfWeek.Monday);

 

SetTime(hour)
SetTime(hour, minute)
SetTime(hour, minute, second)
SetTime(hour, minute, second, millisecond)
These four overloads can be used to get a DateTime representing a different time of day on the same date as the instance it is called on. For instance, if we want to get a DateTime representing 11am today:

DateTime lunchTime = DateTime.Now.SetTime(11);

 

Almost Fluent

Since each of these methods in turn return a new DateTime instance, they can be chained together in a way resembling fluent interfaces. For example, say I wanted to represent half past two PM, next Tuesday:

DateTime lateLunchWithCustomer = DateTime.Now.Next(DayOfWeek.Tuesday).SetTime(14,30);

 

Or maybe I want to represent midnight on the second Monday of the month:

DateTime secondMondayOfMonth = DateTime.Now.First(DayOfWeek.Monday).Next(DayOfWeek.Monday).Midnight();

 

Go Get It!

I've created a project and uploaded the source code for the extension methods and accompanying unit tests to Codeplex - as much for having an excuse to test Codeplex, as for the fact that the methods I've knocked together this evening could just be the beginnings of a larger and more useful set of extensions for the DateTime class.

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Preserving Stack Traces When Re-Throwing Inner Exceptions

An entry about c# 3.0 Publication date 14. March 2008 21:54

In the AOP framework I've been blogging about lately, all member invocations are done through reflection. One side-effect of this, is that if you have any exception handling in your application which expects some specific exception type, it will fail because all exceptions thrown are wrapped in a TargetInvocationException as a result of the reflection. Now the solution might sound simple - the framework should just catch any TargetInvocationExceptions and 'unwrap' them, re-throwing the inner exception instead. There's one huge pitfall here though - catching and re-throwing an exception causes the stack trace to be reset.

Let's look at an example. Here's a program that'll reproduce the scenario:

using System;
using System.Reflection;
 
namespace PreserveStackTrace
{
    class Program
    {
        static void Main(string[] args)
        {
            InvokeRealMethodByReflection(args);
        }
 
        public static void RealMethod(object arg)
        {
            throw new ArgumentNullException("arg");
        }
 
        private static void InvokeRealMethodByReflection(string[] args)
        {
            MethodInfo method = typeof(Program).GetMethod("RealMethod");
 
            object arg = null;
 
            method.Invoke(null, new object[] { arg });
        }
    }
}

 

Running this, we get a "TargetInvocationException was unhandled" error, with the ArgumentNullException as the inner exception, with the following stack trace:

at ConsoleApplication3.Program.RealMethod(Object arg) in {...}\\Program.cs:line 15

 

With line 15 being the "throw new ArgumentNullException("arg");" in the above code (count them if you want :p). We don't want a TargetInvocationException to be thrown, though; we want the ArgumentNullException to be the one the calling code has to deal with.

Re-Throw to the Re-scue?

To fix this, we might try refactoring the InvokeRealMethodByReflection method to the following:

private static void InvokeRealMethodByReflection(string[] args)
{
    MethodInfo method = typeof(Program).GetMethod("RealMethod");
 
    object arg = null;
 
    try
    {
        method.Invoke(null, new object[] {arg});
    }
    catch(TargetInvocationException ex)
    {
        throw ex.InnerException;
    }
}

 

Here, we've unwrapped the TargetInvocationException and re-thrown the inner exception. Thus, the exception that bubbles up to the Main method is the ArgumentNullException - but if we look at the stack trace, we've lost valuable information about the where it occurred:

at PreserveStackTrace.Program.InvokeRealMethodByReflection(String[] args) in {..}\Program.cs:line 30
   at PreserveStackTrace.Program.Main(String[] args) in {..}\Program.cs:line 10
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

 

According to this, the cause of the exception was the InvokeRealMethodByReflection method, on line 30 - but that is the "throw ex.InnerException;" line! We've lost the information we had earlier about what was really the offending method and line of code, because the stack trace got reset when we re-threw the inner exception.

Solving Our Reflection Woes with More Reflection

A mountain bike mechanic I once knew used to say that if a bit of force won't straighten a rim, you're just not applying enough of it. Chris Taylor uses the same mentality to solve the problem I've described here; he's applying a bit more reflection to straighten out the stack trace problem caused by the use of reflection in the first place. His solution is basically to copy across the stack trace from the TargetInvocationException and sticking it into the inner exception before re-throwing it - quite brilliant in it's simplicity (if the rim is bent, just unbend it!).

private static void InvokeRealMethodByReflection(string[] args)
{
    MethodInfo method = typeof(Program).GetMethod("RealMethod");
 
    object arg = null;
 
    try
    {
        method.Invoke(null, new object[] {arg});
    }
    catch(TargetInvocationException ex)
    {
        FieldInfo remoteStackTraceString = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
        remoteStackTraceString.SetValue(ex.InnerException, ex.InnerException.StackTrace + Environment.NewLine);
 
        throw ex.InnerException;
    }
}

 

Now, if we re-run the app, we get the desired ArgumentNullException and the desired stack trace:

at PreserveStackTrace.Program.RealMethod(Object arg) in {...}\Program.cs:line 15
   at PreserveStackTrace.Program.InvokeRealMethodByReflection(String[] args) in {...}\Program.cs:line 33
   at PreserveStackTrace.Program.Main(String[] args) in {...}\Program.cs:line 10
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Currently rated 5.0 by 4 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

A Type Safe ExpectCall Extension Method for Reflective TypeMocks

An entry about tdd | c# 3.0 Publication date 28. January 2008 23:48

Lately, I've been upping the ante on my unit testing skills, which has led me to the awesome mocking framework called TypeMock. Basically, it uses the Profiling API to perform some AOP magic which allows just about anything to be mocked - without it having been explicitly designed for testability, which the merits of is a heavily debated issue.

Imagine that we have the following code that we want to test:

public class Foo
{
    public void DoSomething()
    {
        Logger.Instance.Log("Logging something");
    }
}
 
public class Logger
{
    private Logger() { }
 
    public static readonly Logger Instance = new Logger();
 
    public void Log(string message)
    {
        // logs message to a table in the database
    }
}

 

Normally, writing a unit test for the Foo.DoSomething method would be painful, because we would have to deal with the fact that the Log method it calls needs a database to do its thing, even though we don't really care about the Log method (it should have its own test to verify its correctness, after all).

If we were designing for testability, we would solve this by implementing the logging as a pluggable API so that we could inject a dummy implementation of it that didn't depend on any external resources when testing the Foo class. However, oftentimes the ability to inject a mock implementation of some API turns out to only be a requirement to make the code testable, leading us to sacrificing the cohesion of our code in favor of loose coupling.

With TypeMock, however, we can write our test like this:

[TestMethod]
public void TestDoSomething()
{
    MockManager.Init();
    Mock loggerMock = MockManager.Mock<Logger>();
 
    loggerMock.ExpectCall("Log").Args("Logging something");
 
    Foo foo = new Foo();
    foo.DoSomething();
 
    MockManager.Verify();
}

 

What we're doing here, is telling TypeMock that we want to mock the Logger class, and that the next call to the method Log should be intercepted and faked, instead of actually calling the real method. Additionally, we tell it that we expect the method call to have the argument 'Logging something'. At the end of the test, we ask TypeMock to verify our expectations, and fail the test if any were not met.

It would be much better, though, if I could tell TypeMock this in a type-safe manner, because unit tests are, naturally, written very early on in the coding - there are bound to be countless refactorings of class and method names afterwards. With the above test, however, if I rename the Log method then the test will break.

Now, TypeMock does have a solution for this called Natural TypeMocks, but sadly its not available in the free edition of the framework. So, until I can convince the people in charge of the money at my firm to shell out for licenses to all our devs, I've come up with a neat little extension method inspired by the ASP.NET MVC Toolkits clever use of expression trees to do runtime analysis of lambdas. With it, I can rewrite my above test to:

[TestMethod]
public void TestDoSomething2()
{            
    MockManager.Init();
    Mock loggerMock = MockManager.Mock<Logger>();
 
    loggerMock.ExpectCallAndVerifyArguments<Logger>(l => l.Log("Logging something"));
 
    Foo foo = new Foo();
    foo.DoSomething();
 
    MockManager.Verify();
}

 

Now that is pretty damn cool if you ask me :) Obviously, it has a few limitations - most notably it will only for public members on non-static classes. Regardless, I think it might prove pretty useful - at least until I can get my hands on a license for the Professional or Enterprise edition :p

Here's the code for the extension method:

public static class MockExtensions
{
    public static void ExpectCallAndVerifyArguments<T>(this Mock mock, Expression<Action<T>> expression)
    {
        // get the call expression
        MethodCallExpression call = expression.Body as MethodCallExpression;
 
        // which allows us to pick out the method name
        string methodName = call.Method.Name;                    
 
        // which we can use to set the method call expectation
        IParameters callResult = mock.ExpectCall(call.Method.Name);
 
        // next, we figure out what parameters the expression contains, if any
        // following code is based on the ASP.NET MVC Toolkit LinkExtension.cs implementation
        ParameterInfo[] parameters = call.Method.GetParameters();
 
        if (parameters.Length > 0)
        {
            List<object> args = new List<object>();
 
            for (int i = 0; i < parameters.Length; i++)
            {
                ParameterInfo parameter = parameters[i];
                Expression arg = call.Arguments[i];
                object value;
                ConstantExpression ce = arg as ConstantExpression;
 
                if (ce != null)
                {
                    // If argument is a constant expression, just get the value
                    value = ce.Value;
                }
                else
                {
                    // Otherwise, convert the argument subexpression to type object,
                    // make a lambda out of it, compile it, and invoke it to get the value
                    var lambda = Expression.Lambda<Func<object>>(Expression.Convert(arg, typeof(object)));
 
                    try
                    {
                        value = lambda.Compile()();
                    }
                    catch
                    {
                        value = null;
                    }
                }
 
                args.Add(value);
            }
 
            // set the list of expected parameters
            callResult.Args(args.ToArray());
        }
    }
}

 

In case you couldn't read it between the lines of this post - I'm really exited about TypeMock. So far I've only barely scratched the surface of it, and already its helped me broaden my understanding of unit testing, and allowed me to do really cool things like the above - strong indications of a truly great product, I'd say. So far I've only experimented with implementing an extension method for call expectations, but similar extensions should be easily applicable to other parts of the mocking functionality of TypeMock - I might do a follow-up post with more on this topic in the not too distant future :)

Be the first to rate this post

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

The Atomicity of Variable References

An entry about c# 3.0 Publication date 25. November 2007 13:05

In most object oriented programming languages (like C# and Java) variable references support atomic assignment, even though the storing of a value into a variable really requires two primitive operations - a store and a write. The promise made by the CLR that simple assignments such int num = 1; is atomic, is really a promise that a context switch will never occur between the store and write operations required to execute that statement - essentially, the two operations are treated as one. Consider the following, though:

int num = 1;
++num;

The initial assignment we know is atomic - but what about the increment? To quote from the C# Language specification, "there is no guarantee of atomic read-modify-write, such as is the case of increment and decrement". ++num is really a shorthand for num = num + 1, which results in fetching num from memory, storing it in a register, storing the 1 in a register, performing the add on the two, and then storing the result back into the memory originally allocated to the num variable. That's a much more complex set of instructions being carried out, and in a multi-threaded environment we'd run the risk of a context switch happening in the middle of carrying them out (ie. the execution being halted on one thread and resumed on another), possibly leading to a loss of data integrity. To safeguard against this, we need to synchronize the operation. Fortunately, the framework has a set of methods that deal specifically with synchronizing increments and decrements efficiently:

int num = 1;
System.Threading.Interlocked.Increment(ref num);

Reference Types Too!

It is not only (most) value types that can be atomically assigned, however - the rule also holds for reference types. So for example, the CLR ensures that the following assignment is atomic:

Person p = new Person("Fredrik");

Considering what we discussed above this may seem a bit strange, because surely we have an even more complex set of operations going on than simply incrementing an integer. However, remember that we evaluate the right side of an assignment before assigning it to the variable. So first, we construct the new object instance, and then we assign it to the variable. Until the object is properly constructed, nobody else can access it, and thus we can safely say the assignment is atomic. Note that this does not mean that the constructor is implicitly synchronized, however - if the constructor accesses any shared resources then it is up to you to synchronize access to these. But the assignment itself is safe.

Complex Assignments

So far, we've talked about atomic assignments. We touched upon the idea of complex assignments with the increment example, but really what I mean with a complex assignment is something like, say, the following property Friends on an imaginary Person class:

private IList<Person> _friends = null;
public IList<Person> Friends
{
get
    {
if (null == _friends)
{
_friends = new List<Person>();
_friends.Add(new Person("Bob"));
_friends.Add(new Person("Joe"));
}
return _friends;
}
}

Here, we've implemented a really naive lazy loaded property. The first time it is accessed, the list is created and populated. The assignment of the _friends variable is said to be complex because it entails several operations before it is in the desired state - basically we have to both construct and then initialize it (adding the Bob and Joe items to the list). I'm sure you can see what might happen here - if a context switch were to occur after the construction of the object but before the two items have been added, then another thread may come along and find an empty list when accessing the Friends property. Let's solve this. Consider the following improvement:

private IList<Person> _friends = null;
public IList<Person> Friends
{
get
    {
if (null == _friends)
{
List<Person>  temp = new List<Person>();
temp.Add(new Person("Bob"));
temp.Add(new Person("Joe"));
_friends = temp;
}
return _friends;
}
}

By introducing a temporary variable to hold the list until we've both constructed and initialized it, we 'fake' an atomic assignment, effectively ensuring our data integrity. Bart De Smet recently wrote an interesting post about how the C# 3.0 Object Initializers apply this pattern.

(Super-)Synchronize Me

There's one potential problem with the above, though - it is not synchronized. This means that we may actually end up constructing and assigning the list several times. Imagine that a context switch happens after thread A has evaluated the if condition and found the list to be null, entering the if scope. This thread will now construct and initialize the list, and then assign it to the backing field of the property. However, the context switch lets thread B access the property before thread A has a change to assign the list it is creating to the _friends field - so thread B also sees that _friends is null, and starts to create its own list. In most cases, this won't have any bad side effects apart from a possibly insignificant performance hit, but it can easily be disastrous. What if Thread B executed this:

IList<Person> friends = person.Friends;

When the context switches again, thread A will assigns the list it created list to _friends, orphaning the one thread B created - the reference that Thread B stored for use later is no longer the same as the one the Person object has - auch! Sometimes this won't matter, but I'm sure you can see the dangers here. Fortunately we can fix this fairly easilly by employing the double-checked locking pattern:

private IList<Person> _friends = null;
private static readonly object _friendsLock = new object();
public IList<Person> Friends
{
get
    {
if (null == _friends)
{
lock (_friendsLock)
{
if (null == _friends)
{
List<Person> temp = new List<Person>();
temp.Add(new Person("Bob"));
temp.Add(new Person("Joe"));
_friends = temp;
}
}
}
return _friends;
}
}

Now, Thread B will block on the lock until thread A has finished constructing and initializing the list. When Thread B is later given the lock, it will test to see if the _friends variable has been assigned anew, see that it has, and skip the if scope. We've effectively ensured that the logic inside the if scope will only ever be executed once.

With increasing demand for multi-threaded applications, the principles discussed here become more and more important to grasp in order to write software that keeps the integrity of its data intact. If you want to know more, a good place to start is Bill Wagner's excellent article 'Write Code for a Multithreaded World' which was published in the August 2007 issue of VisualStudio Magazine.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

NDC 2010

The conference to attend this summer happens June 16th-18th in Oslo, Norway. Are you going? Be sure to catch my talk on AOP while you're there!

 

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS