Koen about .Net

June 28, 2011

Thread safe DateTime for unit testing

Filed under: Development, dotnetmag, Testing — Tags: — koenwillemse @ 16:00

We’ve been using the construction of a wrapper class around the DateTime for unit testing which Ayende described here.

Today one of my colleagues discovered that there is a possibility to run multiple unittests in parallel. How to do that is described here. However, the approach we used with the SystemDateTime class no longer worked, since it uses a static field which caused problem with two tests running at the same time. I tweaked it a bit to fix this, so I wanted to share the code we use for it.

/// <summary>
/// Facade for the System.DateTime class that makes it possible to mock the current time.
/// </summary>
public static class SystemDateTime
{
    [ThreadStatic]
    private static Func<DateTime> now;

    [ThreadStatic]
    private static Func<DateTime> today;

    /// <summary>
    /// Returns the current time as a DateTime object.
    /// </summary>
    public static Func<DateTime> Now
    {
        get { return now ?? (now = () => DateTime.Now.Truncate()); }
        set { now = value; }
    }

    /// <summary>
    /// Gets the current date.
    /// </summary>
    public static Func<DateTime> Today
    {
        get { return today ?? (today = () => Now().Date); }
        set { today = value; }
    }
}

Hope it helps some of you.

January 7, 2011

Unit Test Adapter threw exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. – Part 2

Filed under: Development — Tags: , — koenwillemse @ 09:46

In a previous post I wrote about a problem I had with running unittests, which resulted in an exception with the message ‘Unit Test Adapter threw exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.’.

This morning, on my new project, I ran into the same problem after I deleted my TFS workspace locally and got everything new from the server in a different location (a new workspace). So I looked back at my previous post, tried what I wrote there, and….. still the exception :-(. To see if it would lead to more information, I started the tests in debug mode. And… all tests passed as usually. Strange…
I found the problem eventually. The assembly being tested was strongly named. Because we use the code coverage from the unittests, we had to re-sign the assembly tested after instrumentation and we set this up in the Code Coverage section in the testrunconfig.testrunconfig. Now what was the problem? The path to this key file was wrong! I made the mistake that the location pointed out there was a absolute location, instead of a relative location compared to my testrunconfig. So I changed this, cleaned my solution, rebuild the solution and ran the tests. And all tests passed again.

Another lesson learned. Whatch out that you don’t accidentally have absolute paths when referencing stuff which is located in your source control tree.

June 29, 2010

Fluent assertions release 1.2.2

Filed under: Development — Tags: , , — koenwillemse @ 15:44

The last few days I’ve been working on a new release of the Fluent Assertions, since I’ve started using them again on my current project. I ran into a bug myself and saw a few bugs and feature requests on the issue tracker, so I decided to fix some of them.

I just released version 1.2.2 so you can download it here.

The following fixes / new features are available:

Hope these fixes will also be helpful to you all. Download the latest release now and let us know if you have any suggestions of bugs found.

October 27, 2009

Unit Test Adapter threw exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Filed under: Development — Tags: , — koenwillemse @ 10:36

I’ve been banging my head on this error for the last hour. I tried to run a set of unittests from the project we’re currently working on. The tests worked fine.
Then I took my shelveset and for some reason the tests didn’t execute anymore and all gave the error message “Unit Test Adapter threw exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.”. What???

First I tried all the default actions for trying to resolve problems with running tests:
1. Clean the solution
2. Complete rebuild of the solution
3. Refresh the Test View window.
4. Closing Visual Studio and reopening the solution

Unfortunately, none of these actions had the desired effect.

Eventually I was comparing all changes made to the code in source control. What I noticed was a difference in the solution file. The following three lines were missing:

GlobalSection(TestCaseManagementSettings) = postSolution
    CategoryFile = Solution.vsmdi
EndGlobalSection

I added these lines again and it worked :-).

Those vsmdi files are driving me crazy sometimes. Haven’t used them for anything yet and got a lot problems of them when building and running tests (for a while Visual Studio kept adding them; at one point I had 20 vsmdi files in my solution directory).

But to make the story short, I can run the tests again and it had to do with something missing in the solution file.

July 14, 2009

Custom assertions in unittests

Filed under: Development — Tags: , — koenwillemse @ 15:00

One of my collegues has been creating a project with custom assertions to be used in unit tests. The idea behind this is that those assertions make your unittests more readable. You get a notation like something.Should().NotBeNull("woops") instead of Assert.IsNotNull(something, "woops").

At first I was not really impressed with it and didn’t see much improvement in it, but that was because I only saw a few small examples. We’re using it also in our unittests and I must say that it makes it more readable, so check out this blog post that he made about it:
http://blog.avivasolutions.nl/archive/2009/06/27/custom-assertions-make-your-tests-more-readable.aspx

June 11, 2009

Custom enterprise library logging extender for easy overview of logging in unit tests

Filed under: Development — Tags: , , , — koenwillemse @ 14:59

We have been working on a full new .Net architecture at the recent customer I’m working for. We use a lot of tooling / guidance provided by the Patterns and Practices group of Microsoft. One of the components we are using is the Logging Application Block (part of the Enterprise Library 4.1).

We use a facade which we created to write logentries, which are stored in a file, etc. etc. etc… We also have this functionality in our unit tests which creates one huge log file every time we run all the tests. Very frustrating if you want to find a query that was executed or something like that. We added some markers before and after every unittest, but still, not so great.

Today I implemented a very simple solution for this. I created a custom listener which I configured to be used in the unittest project. The code looks like this:

using System;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;

namespace DemoCode
{
    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class ConsoleTraceListener : CustomTraceListener
    {
        /// 
        /// Writes trace information, a data object and event information to the listener specific output.
        /// 
        /// A  object that contains the current process ID, thread ID, and stack trace information.
        /// A name used to identify the output, typically the name of the application that generated the trace event.
        /// One of the  values specifying the type of event that has caused the trace.
        /// A numeric identifier for the event.
        /// The trace data to emit.
        /// 
        /// 	
        /// 	
        /// 
        public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, 
                                       int id, object data)
        {
            var logEntry = data as LogEntry;
            if ((logEntry != null) &amp;&amp; (Formatter != null))
            {
                WriteLine(Formatter.Format(logEntry));
            }
            else
            {
                WriteLine(data.ToString());
            }
        }

        /// 
        /// When overridden in a derived class, writes the specified message to the listener you create in the derived class.
        /// 
        /// A message to write. 
        ///                 2
        public override void Write(string message)
        {
            throw new NotImplementedException();
        }

        /// 
        /// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator.
        /// 
        /// A message to write. 
        ///                 2
        public override void WriteLine(string message)
        {
            Console.WriteLine(message);
        }
    }
}

Writing to the Console has as an effect that it is displayed in the Test Result View.
Next configure it in the app.config of the testproject and voila, the result when running a test:

The result

The result


Simple right? Why didn’t we think of that earlier…
Just one small thing; we use specific widths for the columns in the logging, which looks good in the plain text log file, but not nicely aligned in the result view for the test. Whatever, the information is there, if it must be nicely aligned, copy/paste it a text editor ;-).

See ya,
Koen

Blog at WordPress.com.

%d bloggers like this: