beaucrawford.net

Give me data or give me death

About the author

Author Name is someone.
E-mail me Send mail

Recent comments

Don't show

Authors

Tags

Don't show

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2012

    CoreDateTime.Now - The Future is Now

    Like most developers, I often find myself dealing with code that references DateTime.Now. For example consider this code that retrieves items relative to the current date/time:

    var command = new SqlCommand();
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "GetItems";
    command.Parameters.Add(new SqlParameter("TargetDate", DateTime.Now));

    It would be hard to develop an integration test for this code since it references DateTime.Now. What if I wanted to test the scenario where items with a future date/time value needed to be retrieved, i.e. how will the system behave six months from now? A simple, but very effective, way to deal with this is to add the following class:

    public class CoreDateTime
    {
        static CoreDateTime()
        {
            Executor = () => DateTime.Now;
        }
    
        internal static Func Executor
        {
            get;
            set;
        }
    
        public static DateTime Now
        {
            get
            {
                return Executor();
            }
        }
    }

    The key thing to note here is that the "Executor" property is simply a Func that wraps a call to the normal DateTime.Now. This means that CoreDateTime.Now will behave exactly like DateTime.Now.

    You will also notice that the "Executor" property uses the internal access modifier. This allows testing assemblies to inject a Func of their choosing. You can expose this property to test assemblies using the System.Runtime.CompilerServices.InternalsVisibleTo assembly attribute and then update it with code like:

    CoreDateTime.Executor = () => DateTime.Parse("5/10/2013 10:15 AM");

    You can also have successive calls to CoreDateTime.Now be evaluated against a fixed point in time. This allows you to easily jump to any point of time in the past or future. This code might look like:

    var init = DateTime.Now;
    CoreDateTime.Executor = () => dateTimePicker1.Value.AddSeconds((DateTime.Now - init).TotalSeconds);                

    Happy time travels!


    Categories: C# | Testing
    Posted by Beau on Saturday, June 27, 2009 10:13 AM
    Permalink | Comments (0) | Post RSSRSS comment feed

    Hosting an ADO.NET Data Service inside an NUnit Integration Test Fixture

    This post is geared towards ADO.NET Data Services but the techniques used here could really be used to perform integration testing for any WCF service. 

    First off, yes, I realize that you can test the vast majority of your service functionality outside of an actual service -- after all, there’s no reason for us to test the networking code somebody at Microsoft wrote.  But lets assume that, for some reason, you wanted to perform a full-blown integration test for your ADO.NET Data Service.  How can we do it?  A few notes to get started:

    1) The service needs to start before any tests execute.  We can accomplish this by using the TestFixtureSetup attribute in NUnit.

    2) The service needs to run in its own thread.  This is because it will service requests that originate from tests in the same test fixture.  NUnit executes all methods within the fixture synchronously.  If the service started and blocked while waiting for requests then that would be a very bad thing – as the test run would never complete and no tests would be executed.

    3) The service needs to handle requests for the lifetime of the test fixture and no longer.  We can make this happen by using an AutoResetEvent instance.  This will cause the thread that’s hosting the service to block until it receives a signal.  We can initiate this signal from a method that is adorned with the TestFixtureTeardown attribute.  NUnit executes all methods with this attribute after it executes all methods adorned with the "Test attribute. This will allow the service to close and dispose of itself.

    private static readonly Uri serviceUri = new Uri("http://localhost:1642/MyService.svc");
    
    private static AutoResetEvent serviceResetEvent = new AutoResetEvent(false);
    
    [TestFixtureSetUp]
    public void FixtureSetup()
    {
        Action runService = () =>
        {
            using (var host = new WebServiceHost(typeof(MyService), serviceUri))
            {
                host.Open();
                serviceResetEvent.WaitOne();
                host.Close();
            }
        };
    
        var thread = new Thread(new ThreadStart(runService));
        thread.Start();
    }

    The key thing to notice here is that the AutoResetEvent instance starts with its initial state == false.  This will cause calls to the “WaitOne” method to block until a signal is sent using the “Set” method – which is exactly what we need to do in the test fixture tear down operation:

    [TestFixtureTearDown]
    public void FixtureTearDown()
    {
        serviceResetEvent.Set();
    }

    We can now create integration tests that actually call the Data Service.  A simple example might be:

    [Test]
    [Category("Integration")]
    public void DataServiceIntegrationTestExample()
    {
        DataServiceContext context = new DataServiceContext(serviceUri);
    
        DataServiceQuery query =
            context.CreateQuery< MyType >("MyMethod")
            .AddQueryOption("someParameter", "'someValue'");
    
        var results = context.Execute< MyType >(query.RequestUri);
    
        Assert.IsTrue(results.Count< MyType >() == 1);
    }

    This will create a WCF service request which will get served by the service instance created in the test fixture setup method.


    Categories: WCF | C# | Testing
    Posted by Beau on Tuesday, March 24, 2009 11:58 PM
    Permalink | Comments (2) | Post RSSRSS comment feed

    Testing Work Flow Dependencies with Rhino Mocks 3.5

    We’re currently working on a custom Work Flow system (no, not Windows Work Flow) that utilizes MSMQ.  To make each work flow node highly testable what I decided to do was create an abstraction of the items I needed from the System.Messaging.MessageQueue class.  This abstraction is an interface named IMessageQueue.  The next thing was to create a “QueueServer” class that obtains an instance of IMessageQueue via a simple Inversion of Control container named QueueResolver.

    QueueServer Start method:

    public void Start()
    {
        Queue = QueueResolver.Current.CreateInstance(Path, Transactional);
    
        if (Transactional)
        {
            Queue.PeekCompleted += PeekCompleted;
            Queue.BeginPeek();
        }
        else
        {
            Queue.ReceiveCompleted += ReceiveCompleted;
            Queue.BeginReceive();
        }
    }


    The default implementation of the QueueResolver class is quite simple (yes, i know we could use any of the common IOC containers to achieve this – but I like this approach for some specific situations since it is more lightweight and I don’t have to worry about maintaining a .config file, etc):

    public class QueueResolver
    {
        static QueueResolver()
        {
            Current = new QueueResolver();
        }
    
        public static void Initialize(QueueResolver resolver)
        {
            Validate.NotNull("resolver", resolver);
    
            Current = resolver;
        }
    
        public static QueueResolver Current
        {
            get;
            private set;
        }
    
        protected QueueResolver()
        {
        }
    
        public virtual IQueueClient< T > CreateClient< T >(string name, string path, bool transactional)
            where T : class, IFlowObject< long >
        {
            return new QueueClient< T >(name, path, transactional);
        }
    
        public virtual IQueueServer< T > CreateServer< T >(string name, string path, bool transactional)
            where T : class, IFlowObject< long >
        {
            return new QueueServer< T >(name, path, transactional);
        }
    
        public virtual IMessageQueue CreateInstance(string path, bool transactional)
        {
            Validate.NotNullOrEmpty("path", ref path);
    
            MessageQueue queue;
    
            if (MessageQueue.Exists(path))
            {
                queue = new MessageQueue(path);
            }
            else
            {
                queue = MessageQueue.Create(path, transactional);
            }
    
            queue.Formatter = new BinaryMessageFormatter();
    
            return new MessageQueueProxy(queue);
        }
    }


    This ends up being a very simple way for me to break the dependency on an actual MSMQ instance and allows me to inject test doubles of IMessageQueue with some simple code like:

    const string Name = "Test Queue";
    const string Path = @".\Private$\TestQueue";
    const bool Transactional = true;
    
    var resolver = MockRepository.GenerateStub< QueueResolver >();
    var queue = MockRepository.GenerateMock< IMessageQueue >();
    resolver.Stub(r => r.CreateInstance(Path, Transactional)).Return(queue);
    
    QueueResolver.Initialize(resolver);

    The advantage to all this, of course, is that I can now use Rhino Mocks to test the inner functionality of the QueueServer by utilizing this Dependency Injection technique:

    bool eventRaised = false;
    
    var customer = MockRepository.GenerateStub< ICustomer >();
    var server = new QueueServer< ICustomer >(Name, Path, Transactional);
    
    server.ItemReceived += delegate(object sender, QueueEventArgs< ICustomer > e)
    {
        eventRaised = true;
        Assert.AreSame(e.Item, customer);
    };
    
    server.Start();
    
    var message = new Message();
    message.Body = customer;
    queue.Raise(q => q.PeekCompleted += null, queue, new EventArgs< message >(message));
    
    Assert.IsTrue(eventRaised);

    We also have a QueueClient class that obtains an instance of IMessageQueue in the same manner.  With these two classes we will be able to easily model our work flow and completely unit test the interaction between the queues.  Also we will be able to easily unit test the entire lifespan of a “flow object” and write robust unit tests to track it throughout the work flow.


    Categories: C# | Design Patterns | Testing
    Posted by Beau on Sunday, March 15, 2009 10:35 AM
    Permalink | Comments (0) | Post RSSRSS comment feed