twisted word

words on development

Deploying a nested express app from git to heroku

without comments

I have a git repo that has more than just an express app. For example, the repo structure looks a bit like this:

./
    site/
        app.js

Deploying via git push heroku master was failing with the error message, ‘no Cedar-supported app detected’. It seems that heroku expects the “app” to be in the root directory.

A lot of comments out there suggest moving the site to its own repo. I didn’t want to do this. Here is the work-around:

  1. move app’s package.json file to the root folder of the repo
  2. move Procfile to the root folder of the repo
  3. modify the Procfile accordingly to include the path to the app.js file

Written by twisted

September 21st, 2012 at 1:50 pm

Posted in Uncategorized

Tagged with ,

Headless auto (continuous) testing of Backbone.js app with jasmine.js

without comments

Finding info on this was a PITA.  Most of the search results point to jasmine-headless-webkit.  I have a project that I want to be able to work on anywhere which means I need to be able to work on Windows, Mac & Linux.  That quickly ruled out the jasmine-headless-webkit.  Not that it couldn’t be done (not sure), but I didn’t want to install a bunch of compilers.  The first dependency issue I ran into was qt4-make.  After installing the qt tools, I was missing gmake.  So I stopped.  For some reason, I’ve never liked cygwin.  I’ve got my own collection of unix utilities that I’ve collected over the years and keep in a bin folder (including tcsh…take that bash’ers).

Anyway, onto the point.  I think I have it.  Here are the steps to get this setup:

  1. Install ruby
  2. Install node.js
  3. Install npm
  4. Install jessie:  npm install -g jessie (specs wouldn’t run if this wasn’t installed globally; unfortunately, couldn’t get sugar to work)
  5. Install guard:  gem install guard
  6. Install guard-jessie:  gem install guard-jessie
  7. Install backbone for node.js:  npm install backbone (must be local to your project)
  8. (Windows only): Install win32console:  gem install win32console

The guard-jessie readme has instructions for creating the Guardfile.  You’ll want to create this at the root of your app and then modify to fit your paths.  Here is what mine looks like:

guard 'jessie' do
  watch(%r{^spec/.+(_spec|Spec)\.(js|coffee)$})
  watch(%r{^app/assets/js/(.+)\.(js|coffee)$}) { |m| "spec/app/#{m[1]}_spec.js" }
  watch('spec/spec_helper.js') { "spec" }
end&

I know nothing about guard, but here is what I’ve surmised about the “watch” lines:

Line 1:  watches for any changes to your spec files. Runs the spec that changed
Line 2:  watches for any changes to your application files.  Runs the matching spec.
Line 3:  watches for any changes to the spec helper.  Runs all specs

jessie has the requirement that your tests be placed in a folder called “spec”.  In that folder, you’ll place your spec_helper.js.  To test Backbone.js, you’ll need to add the following line:

Backbone = require('backbone')

To kickoff the continuous testing, navigate to the location of the Guardfile and enter the command:  guard start.

That’s it. Continuous testing of Backbone.js apps.

Written by twisted

February 16th, 2012 at 11:58 pm

Waiting for sitecorewebsite…

without comments

I see this a lot these days, just wanted to post to remember the good times.

Written by twisted

January 5th, 2011 at 11:57 am

Posted in Uncategorized

NHibernate, WCF and Unity (oh, and testing)

without comments

Context

On my current project, we ran into a bit of a hiccup in trying to get NHibernate, WCF and Unity working together smoothly.  This was a greenfield project, but the only one of those technologies involved from the beginning was NHibernate.  The project was originally for a WinForms application, but eventually WCF services needed to be added to allow external parties access to common domain services.

No DI framework was chosen initially, so we implemented a poor man’s DI class that totally violated SRP. This class acted as both the DI container and the UnitOfWork implementation.  Oh, and it was a singleton (not so much for the UoW bit, but more for the NHibernate initialization).   I’m probably mostly to blame for that poor judgment…so, for this article, let’s call the interface for the beast IDIOTContainer (Interface for Dependency Injection Of Things Container).

Fast forward a few months year and someone on the team chooses Unity.  Yay.  So now we have DI, but we’re still passing around this IDIOTContainer.  This in spite of the fact that we had a technical debt mess item to replace the IDIOTContainer with DI and UnitOfWork implementations once a DI framework had been chosen.  Instead, someone created an wrapper class for the container that could be instantiated by Unity and still use the singleton.  More fun!

The end result:  a singleton UOW that manages sessions and transactions as well as handing out repositories.  As it turns out, this as well as how we were handling the NHibernate SessionFactory caused multiple problems when we tried to reuse our domain services and DAL layer inside a WCF service.

Issue 1: Race condition on NHibernate SessionFactory

The first issue encountered was a race condition when constructing the NHibernate ISessionFactory.  When a WCF service was called concurrently, each call would attempt to build up the factory.  I don’t remember the exact exceptions (and there were different ones, depending on the timing), but the only way to let the consuming team move forward was to throttle the number of concurrent connections to 1. 

How to fix…

Our NHibernate session manager (the class responsible for constructing the NHibernate Session Factory and handing out Sessions) would construct the session factory on the first request for a session…something like this:

	public ISession OpenSession()
	{
		EnsureSessionFactoryIsInitialized();
		return SessionFactory.OpenSession();	
	}

So, adding a public method to initialize the factory manually was added.  Then, since the WCF service was hosted by IIS, we added a line to the Application_Start method in a global.asax.  (I wasn’t fond of adding a global.asax to the project, but it seemed to be the simplest solution).

	protected void Application_Start(object sender, EventArgs e)
	{
		NHibernateSessionManager.Initialize();
	}

This removed the race condition.  Next up was to remove the connection throttling and we’re golden…right?  Not quite.

Issue 2:  NHibernate Sessions shared between HTTP Sessions

The ServiceBehavior attribute on the service did not define an InstanceContextMode, so by default it was PerSession.  Quick fix, add InstanceContextMode = InstanceContextMode.PerCall to the attribute.  And then…

Issue 3: NHibernate Sessions shared between WCF calls

If you skipped the background, you might not get why this would occur.  In a nutshell:  singleton repository container / unit of work.  The result is NHibernate / ADO.Net exceptions (either something about a DataReader being cExercise/”>Losed or the impropriety of flushing at the wrong time).

Ok, easy enough to fix.

  1. Abstract all members of the singleton class (except the Instance member and private constructor) into a base class
  2. Create a second class (we’ll call this class UnitOfWork, since that is the direction it should head) that implements this base class.
  3. Change the Unity config for our IDIOTContainer to point to the new class, something like this:
	<type type="SomeDomain.IDIOTContainer, SomeDomain" mapto="DAL.UnitOfWork, DAL">

So far, this has been fairly simple.  I didn’t have to delve into the inner workings of NHibernate, Unity or WCF.  All tests pass and we were able to process WCF calls concurrently.  Awesome!  So I go home for the night all tingly.  Then the next morning I get this creeping feeling that I’ve overlooked something.

What happens when different objects request the IDIOTContainer in the same call?  This isn’t trivial…multiple repositories can be involved in the same transaction.  For this to work, they have to get the _same_ UOW object.  By default, Unity will serve up a new instance every time Resolve() is called.  That leads us to the final and hairiest issue:

Issue 4:  UnitOfWork not shared between objects in the same WCF call

Our unit tests wouldn’t catch this because the object resolution was mocked.  Our integration tests wouldn’t catch this unless there was an error inserting data.  We didn’t have a good methodology for testing WCF directly, so I wasn’t even sure how to easily write a failing test (replace one of the NHibernate mappings with a stored procedure that throws an error???).  Oh, and the client wants this in production yesterday. 

I was able to write a test to confirm my hunch about the object resolution.  So now, how do I fix it?  After some initial research, I surmised that it couldn’t easily be fixed via a config change for Unity or WCF.  I would have to delve a bit into the inner workings of both and figure out the simplest solution.  Also, since I wasn’t quite sure how to test it or what needed to change, I couldn’t easily practice TDD which has become such a habit that it felt a bit like coding without a net.  I was really concerned that I would waste time writing code that I wouldn’t need. 

What I needed to have happen was this:

  • When an operation is called (and a UnitOfWork is needed) only one UnitOfWork should be created and then passed around to internal objects that need it
  • This should just happen.  We have the technology.

The first point meant I would have to do something on the WCF side and the second point meant that I would have to do something on the Unity side.  I’m not a big fan of Unity, so let’s look at the WCF side first.

WCF

So, I need some way to put a UnitOfWork into the context of the WCF service call.  I had two options:

  1. OperationContext
  2. InstanceContext

Since our services were marked with InstanceContextMode.PerCall, using either should give us the same result.  And we may want to share UnitOfWork between operations in the future, so I chose to work with the InstanceContext.

The first step was to create an extension object for the InstanceContext (by implementing IExtension)

    public class MyContext : IExtension<InstanceContext>
    {
        private Dictionary<Type, object> _contextBag;

        public T Get<T>()
        {
            if (_contextBag.ContainsKey(typeof (T)))
            {
                return (T) _contextBag[typeof (T)];
            }

            return default(T);
        }

        public void Add<T>(object instance)
        {
            if (_contextBag.ContainsKey(typeof (T))) return;

            _contextBag.Add(typeof (T), instance);
        }

        public void Remove<T>()
        {
            _contextBag.Remove(typeof (T));
        }

        public void Attach(InstanceContext owner)
        {
            _contextBag = new Dictionary<Type, object>();
        }

        public void Detach(InstanceContext owner)
        {
            _contextBag = null;
        }
    }

Now that I have something to hold my UnitOfWork (and other objects, if needed), I need to inject this into the InstanceContext and have that happen when the call occurs.  A few of the suggestions (listed below) I found involved creating an IMessageInspector and a custom attribute to get this stuff injected into the WCF call.  However, I found a clever solution that mixed the two in a single class.  I mention this in case you need more fine-grained control over the WCF call lifecycle.  Without further ado, here is the custom attribute that also adds my custom context object into the InstanceContext.Extensions collection:

    public class MyContextBehaviorAttribute : Attribute, IContractBehavior, IInstanceContextInitializer
    {
        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint) { }

        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            dispatchRuntime.InstanceContextInitializers.Add(this);
        }

        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime) { }

        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }

        public void Initialize(InstanceContext instanceContext, Message message)
        {
            instanceContext.Extensions.Add(new MyContext());
        }
    }

By implementing IContractBehavior and IInstanceContextInitializer, I was able to kill two birds with one stone.  When the call comes in, my context extension object will now be available if I decorate my service class with the following attribute:

     [MyContextBehavior]

Unity

Now that I have somewhere to store a UnitOfWork, I need to get Unity to instantiate one for me on the first call and then use the one in the InstanceContext for subsequent resolutions.  Sounds like I need to create my own LifetimeManager.  Some more digging, and I come up with this:

    public class MyContextLifetimeManager<T> : LifetimeManager
    {
        public override object GetValue()
        {
            return GetContext().Get<T>();
        }

        public override void SetValue(object newValue)
        {
            GetContext().Add<T>(newValue);
        }

        public override void RemoveValue()
        {
            GetContext().Remove<T>();
        }

        private static MyContext GetContext()
        {
            return OperationContext.Current.InstanceContext.Extensions.Find<MyContext>();
        }
    }

The key here is the private method GetContext.  This retrieves the MyContext object from the WCF InstanceContext.  Sweet.  The last step was to add the custom LifetimeManager to the Unity config for IDIOTContainer / UnitOfWork.  Or not.  It could be because we are using Unity v1.1 or my lack of patience, but because the custom LifetimeManager uses generics, I couldn’t get Unity to use it via xml configuration (even with the “`1″ syntax).  So, here is my hack…back to the global.asax:

	protected void Application_Start(object sender, EventArgs e)
	{
		NHibernateSessionManager.Initialize();
		ObjectLocator.GetContainer().RegisterType<IDIOTContainer, UnitOfWork>(
				new MyContextLifetimeManager<IDIOTContainer>());
	}

Ok, a quick run through the mental compiler and everything seems to be in order.  But how do I know for sure?  Test maybe?

Testing

OperationContext & InstanceContext are sealed and do not implement any interfaces.  I don’t remember whose blog(s) I was reading, but the first few suggestions I found for testing WCF context involved creating interfaces to match one of these classes and then changing your WCF implementation to use these interfaces.  Really elegant stuff it seemed, but I didn’t have the time.  I just needed a simple test to see if an object was reused or not.  So, finally, after reading a few great posts, I decided to create a simple service and host it inside of my test assemblies.  I didn’t want to mess with data contracts, so I decided to have the object create a GUID and have the service return that GUID if I needed to check referential equality.  Quick and dirty.  Here is the test object I created:

    public interface IMyContextSpecObject
    {
        Guid Id { get; set; }
    }

    public class MyContextSpecObject : IMyContextSpecObject
    {
        public MyContextSpecObject()
        {
            Id = Guid.NewGuid();
        }
        public Guid Id { get; set; }
    }

For the service, I created two operations.  The first would resolve two test objects from Unity and return whether or not they were the same.  The second would resolve one test object and return its ID so that I could test whether different calls received different test objects.

    [ServiceContract(Namespace = "http://company.com/schemas/specs/MyContext")]
    public interface IMyContextSpecService
    {
        [OperationContract]
        bool IoCObjectsAreEqual();

        [OperationContract]
        string GetMyContextSpecObject();
    }

    [ServiceBehavior(Namespace = "http://company.com/schemas/specs/MyContext", InstanceContextMode = InstanceContextMode.PerCall)]
    //this next line gets added later, to make tests pass
    //[MyContextBehavior]
    public class MyContextSpecService : IMyContextSpecService
    {
        public MyContextSpecService()
        {
    	    //this next line gets added later, to make tests pass
            //ObjectLocator.GetUnityContainer().RegisterType<IMyContextSpecObject, MyContextSpecObject>(new MyContextLifetimeManager<IMyContextSpecObject>());
        }

        public bool IoCObjectsAreEqual()
        {
            IMyContextSpecObject objectA = ObjectLocator.Retrieve<IMyContextSpecObject>();
            IMyContextSpecObject objectB = ObjectLocator.Retrieve<IMyContextSpecObject>();

            return objectA.Id.Equals(objectB.Id);
        }

        public string GetMyContextSpecObject()
        {
            return ObjectLocator.Retrieve<IMyContextSpecObject>().Id.ToString();
        }
    }

Now, to host the service inside of a test:

    internal class MyContextServiceHost
    {
        internal static ServiceHost Instance;

        internal static string GetTestAddress()
        {
            return &quot;http://localhost:9999/MyContext&quot;;
        }

        internal static BasicHttpBinding GetTestBinding()
        {
            return new BasicHttpBinding();
        }

        internal static void StartService()
        {
            Instance = new ServiceHost(typeof (MyContextSpecService));
            Instance.AddServiceEndpoint(
			typeof (IMyContextSpecService), 
			GetTestBinding(), 
			new Uri(GetTestAddress()));
            Instance.Open();
        }

        internal static void StopService()
        {
            if (Instance.State != CommunicationState.C<a href="http://www.willbeta.com/lose-weight-<a href="http://www.willbeta.com/lose-weight-exercise/">Exercise</a>/">Lose</a>d)
            {
                Instance.C<a href="http://www.willbeta.com/lose-weight-<a href="http://www.willbeta.com/lose-weight-exercise/">Exercise</a>/">Lose</a>();
            }
        }
    }

This class will create a ServiceHost and setup the binding and endpoint.  Finally, the specs:

    [TestFixture]
    public class When_retrieving_an_object_from_a_DI_container_in_the_context_of_a_My_service_call
    {
        private IMyContextSpecService _client;

        [TestFixtureSetUp]
        public void SetUp()
        {
            MyContextServiceHost.StartService();

            _client = ChannelFactory<IMyContextSpecService>.CreateChannel(MyContextServiceHost.GetTestBinding(), new EndpointAddress(MyContextServiceHost.GetTestAddress()));
        }

        [TestFixtureTearDown]
        public void TearDown()
        {
            MyContextServiceHost.StopService();
        }

        [Test]
        public void the_same_object_should_be_used_within_a_given_call()
        {
            Assert.IsTrue(_client.IoCObjectsAreEqual());
        }

        [Test]
        public void different_objects_should_be_used_between_calls()
        {
            string idA = _client.GetMyContextSpecObject();
            string idB = _client.GetMyContextSpecObject();

            Assert.AreNotEqual(idA, idB);
        }
    }

I was able to get the tests to fail at first and then pass by adding the following lines to the MyContextSpecService class (they are already in the code above):


	//following attribute added to service
	[MyContextBehavior]

	//following line added to constructor
	ObjectLocator.GetUnityContainer().RegisterType<IMyContextSpecObject, MyContextSpecObject="">(new MyContextLifetimeManager<IMyContextSpecObject>());

I’ll leave the refactor step for another time.  I’m sure I’ve made some mistakes in here somewhere…diving into WCF seems to be a bit of a rabbit hole and more than I needed to take on at the time.  For now, I’ll just enjoy the red-green glow of proving a prototype without having to debug.

The primary sources that I used to put all of this together can be found here, here, here and here.

Written by twisted

September 11th, 2009 at 9:20 pm

Posted in Uncategorized

Tagged with , ,

Mocking for Fun & Profit: Part 5 – Constraints

without comments

This is a continuation of a series of articles on using RhinoMocks 3.5 AAA features…

Constraints are useful when you want to limit the stubbing of method calls to certain conditions or only want to assert that a method was called with particular parameters.  When used in conjunction with delegates (WhenCalled), you can do things like return object A when parameter 1 is passed, object B when parameter 2 is passed, and so on.  Before we walk, let’s learn to crawl.

First, the class used and the spec setup:

    public class ConstraintObject
    {
        public virtual string ReturnThisString(string value)
        {
            return value;
        }

        public virtual bool IsEven(int i)
        {
            return i%2 == 0;
        }
    }

    [TestFixture]
    public class When_constraining_the_arguments_on_a_stubbed_or_expected_method_call
    {
        private ConstraintObject _object;

        [SetUp]
        public void SetUp()
        {
            _object = MockRepository.GenerateMock<ConstraintObject>();
        }
    }

The simplest constraint we can use is a method call IgnoreArguments().  This constraint (or non-constraint, if you prefer) allows all calls to a method to be treated the same regardless of the parameters passed to it:

        [Test]
        public void use_Ignore_Arguments_to_allow_all_arguments_on_a_stubbed_call()
        {
            string thereIsOnlyZul = "Zul";

            _object.Stub(x => x.ReturnThisString(null))
                .IgnoreArguments()
                .Return(thereIsOnlyZul);

            Assert.AreEqual(thereIsOnlyZul,
                            _object.ReturnThisString("Dana"));

            Assert.AreEqual(thereIsOnlyZul,
                            _object.ReturnThisString("something else"));
        }

As shown, when using IgnoreArguments, all stubbed method calls will result in the same return value.

To be a bit more selective, you will want to use the Arg<T> object.  There are a lot of options for this, but for now, we’ll just focus on the simplest:  Arg<T>.Is:

        [Test]
        public void use_Arg_to_define_Constraints_on_the_arguments_of_a_stubbed_call()
        {
            _object.Stub(x => x.IsEven(
                                  Arg<int>.Is.Equal(3)))
                .Return(true);

            _object.Stub(x => x.IsEven(
                                  Arg.Is(4)))
                .Return(false);

            _object.Stub(x => x.IsEven(
                                  Arg<int>.Is.GreaterThan(10)))
                .Return(false);

            Assert.IsFalse(_object.IsEven(4000));
            Assert.IsFalse(_object.IsEven(200));
            Assert.IsFalse(_object.IsEven(12));
            Assert.IsFalse(_object.IsEven(4));
            Assert.IsTrue(_object.IsEven(3));
        }

Here, I am using 2 of the methods available on Arg<T>.IsEqual() and GreaterThan().  Also notice that in the second stub, I’m using a completely different syntax for Arg<T>.Is.Equal().  This is a syntactic shortcut.  The following two lines operate identically:

            _object.Stub(x => x.IsEven(Arg<int>.Is.Equal(5))).Return(true);
            _object.Stub(x => x.IsEven(Arg.Is(5))).Return(true);

The type of the argument is inferred and Equal() is implied as the default.

The samples in these articles were intentionally as simple as possible.  Hopefully, they will help someone on their path to more advanced techniques.  If there are example usages you would like to see, leave a comment and I’ll do my best.

Written by twisted

April 9th, 2009 at 9:11 pm

Mocking for Fun & Profit: Part 4 – Delegating

without comments

This is a continuation of a series of articles on using RhinoMocks 3.5 AAA features…

Many times when setting up mocks for a test, you will need to either examine an object that is passed into a method or return a want to return a different object based on the methods passed into an object. The path of least code is to use a combination constraints and delegates. That might take a bit to get one’s brain wrapped around, so let’s start of with some simple delegates.

If you have used RhinoMocks before v3.5, you might be familiar with the Expect().Do() syntax for delegating method calls:

    Expect.Call(delegate { mockObject.DoSomething(theSomething); })
        .Do(new DoSomethingDelegate(MyDoSomethingHandler));

This was workable, but involved setting up both a delegate and a handler. The new syntax is so much cleaner. With the new syntax, we can use lambdas and anonymous methods.

Here is the class we’ll be testing with (and the spec setup):

    public class WhenCalledObject
    {
        public virtual void CallMe() {}

        public virtual void SomeMethod(int i) {}
    }



    [TestFixture]
    public class When_delegating_the_method_call_on_a_Mocked_object
    {
        private WhenCalledObject _object;
        private int _x;

        [SetUp]
        public void SetUp()
        {
            _object = MockRepository.GenerateMock<WhenCalledObject>();
        }

The new method we’ll be using to delegate a method call is called WhenCalled()WhenCalled takes an Action<MethodInvocation> parameter.  This allows for some very flexible test cases.  Before getting too crazy, let’s start with some basic usages.  Here we see that we can do away with delegates for the simplest of cases and use a lambda:

        [Test]
        public void the_When_Called_method_replaces_the_Expect_Do_syntax_and_allows_lambdas()
        {
            bool wasCalled = false;

            _object.CallMe();
            Assert.IsFalse(wasCalled);

            //this used to be represented by Expect(some call).Do(something with that call)
            _object.Stub(x => x.CallMe())
                .WhenCalled(obj => wasCalled = true);

            _object.CallMe();
            Assert.IsTrue(wasCalled);
        }

Notice the use of the MethodInvocation? Using this object, we can access the arguments passed into our stubbed method.  When combined with constraints, this allows for some very interesting possibilities.

And of course, you can still use delegates:

        [Test]
        public void delegates_can_still_be_used()
        {
            _object.Stub(x => x.SomeMethod(0))
                .IgnoreArguments()
                .WhenCalled(invocation => SomeDelegate((int) invocation.Arguments[0]));

            _object.SomeMethod(42);
            Assert.AreEqual(42, _x);
        }

        private void SomeDelegate(int i)
        {
            _x = i;
        }

Written by twisted

April 9th, 2009 at 8:31 pm

Mocking for Fun & Profit: Contents and Source Code

without comments

Written by twisted

April 9th, 2009 at 7:32 pm

Mocking for Fun & Profit: Part 3 – Mocks

without comments

As mentioned in a previous post, Mocks aren’t stubs. So, let’s jump in and see how mocks differ from stubs (using RhinoMocks 3.5 AAA features).

First up, here is the class that will be used for testing (and the setup of our spec):

    public class MockObject
    {
        public virtual string VirtualProperty { get; set; }

        public string NonVirtualProperty { get; set; }

        public object DoSomething()
        {
            return VirtualProperty;
        }
        
        public virtual object DoSomethingVirtually()
        {
            return VirtualProperty;
        }

        public virtual void MethodThatShouldBeCalled()
        {
            throw new System.NotImplementedException();
        }
    }


    [TestFixture]
    public class When_using_a_Mock_in_a_test
    {
        private MockObject _realObject;
        private MockObject _mockObject;

        [SetUp]
        public void SetUp()
        {
            _realObject = new MockObject();
            _mockObject = MockRepository.GenerateMock<MockObject>();
        }
    }

Properties

Compared to a stub, the properties on a mock act differently depending on whether they are virtual. Non-virtual properties behave like normal properties:

        [Test]
        public void a_mocked_objects_non_virtual_properties_behave_like_normal_properties()
        {
            string testString = "this is a test";
            _realObject.NonVirtualProperty = testString;
            _mockObject.NonVirtualProperty = testString;

            Assert.AreEqual(testString, _realObject.NonVirtualProperty);
            Assert.AreEqual(testString, _mockObject.NonVirtualProperty);
        }

Virtual properties, however, do not act like normal properties and, therefore, must be stubbed:

        [Test]
        public void a_mocked_objects_virtual_properties_do_not_behave_like_normal_properties()
        {
            string testString = "this is a test";

            _realObject.VirtualProperty = testString;
            _mockObject.VirtualProperty = testString;

            Assert.AreEqual(testString, _realObject.VirtualProperty);
            Assert.AreNotEqual(testString, _mockObject.VirtualProperty);
        }

        [Test]
        public void a_mocked_object_requires_its_virtual_properties_to_be_stubbed()
        {
            string testString = "this property never got set";
            _mockObject.Stub(x => x.VirtualProperty).Return(testString);

            Assert.AreEqual(testString, _mockObject.VirtualProperty);
        }

Methods

In contrast to stubs, methods on mocks are never executed regardless of whether they are virtual:

        [Test]
        public void a_mocked_objects_methods_are_never_executed()
        {
            string testString = "test of method";

            _mockObject.VirtualProperty = testString;
            _realObject.VirtualProperty = testString;

            Assert.AreEqual(testString, _realObject.DoSomething());
            Assert.AreNotEqual(testString, _mockObject.DoSomething());

            Assert.AreEqual(testString, _realObject.DoSomethingVirtually());
            Assert.AreNotEqual(testString, _mockObject.DoSomethingVirtually());
        }

If you need to have a method return a value in your test, you will need to either stub the method (or set an expectation on it with a return value):

        [Test]
        public void a_mocked_objects_methods_can_be_stubbed()
        {
            string testString = "test of method";

            _mockObject.Stub(x => x.DoSomething()).Return(testString);
            Assert.AreEqual(testString, _mockObject.DoSomething());
        }

Methods on mocked objects will both verify expectations set on them and verify that they were called. Contrast this with methods on stubs, which can only verify that they were called. These next two tests will use a helper class to call our object under test:

    public class MockObjectHelper
    {
        private readonly MockObject _mockObject;

        public MockObjectHelper(MockObject mockObject)
        {
            _mockObject = mockObject;
        }

        public void CallAMethodOnMockObject()
        {
            _mockObject.MethodThatShouldBeCalled();
        }
    }

And the specs:

        [Test]
        public void a_mocked_object_verifies_expectations_set_on_it()
        {
            MockObjectHelper helper = new MockObjectHelper(_mockObject);
            _mockObject.Expect(x => x.MethodThatShouldBeCalled());

            //commenting out next line will cause test to fail
            helper.CallAMethodOnMockObject();

            _mockObject.VerifyAllExpectations();
        }

        [Test]
        public void a_mocked_object_can_assert_if_one_of_its_methods_was_called()
        {
            MockObjectHelper helper = new MockObjectHelper(_mockObject);

            helper.CallAMethodOnMockObject();
            _mockObject.AssertWasCalled(x => x.MethodThatShouldBeCalled());
        }

For further explanation on the difference between Mocks & Stubs in RhinoMocks, consult the source.

Written by twisted

April 9th, 2009 at 7:22 pm

Mocking for Fun & Profit: Part 2 – Stubs

without comments

What are mocks? What are stubs? Mocks aren’t stubs.  Clear?

Perhaps it would help to look at the capabilities of each (as used in RhinoMocks) to see the difference in implementation.  Although, sometimes I am confused as to the difference (would probably help if I looked through the code).  For the most part, my choice of whether to use a stub or a mock is driven more by coding guidelines than a need for particular functionality.

What I mean is that if I am just providing an object that needs to take up space, I use a stub.  If I need to verify that certain methods or properties were called on an object, I use try to remember to use a mock.  In reality, for about 90% of the cases where I use a mock, a stub would probably accomplish the same thing.

These next two articles will cover some of the functionality provided by stubs and mocks and highlight where the behavior differs.  All of these articles will be using the RhinoMocks 3.5 AAA features.

This is the test class that will be used in this article and the setup of our spec:

    public class StubObject
    {
        public virtual string VirtualProperty { get; set; }

        public string NonVirtualProperty { get; set; }

        public object DoSomething()
        {
            return VirtualProperty;
        }

        public virtual object DoSomethingVirtually()
        {
            return VirtualProperty;
        }

        public virtual void MethodThatShouldBeCalled()
        {
            throw new System.NotImplementedException();
        }

    }

    [TestFixture]
    public class When_using_a_Stub_in_a_test
    {
        private StubObject _realObject;
        private StubObject _stubbedObject;

        [SetUp]
        public void SetUp()
        {
            _realObject = new StubObject();
            _stubbedObject = MockRepository.GenerateStub<StubObject>();
        }

    }

Properties

Properties on a stub behave like normal properties. As the following test demonstrates, we set the properties of a stubbed object if we need them to return a value in our tests:

        [Test]
        public void a_stubbed_objects_properties_behave_like_normal_properties()
        {
            string testString = "this is a test";

            _realObject.VirtualProperty = testString;
            _stubbedObject.VirtualProperty = testString;
            _stubbedObject.NonVirtualProperty = testString;

            Assert.AreEqual(testString, _realObject.VirtualProperty);
            Assert.AreEqual(testString, _stubbedObject.VirtualProperty);
            Assert.AreEqual(testString, _stubbedObject.NonVirtualProperty);
        }

In fact, we cannot stub out the properties on a stubbed object. Trying to do so will generate an exception:

        [Test]
        [ExpectedException(typeof (InvalidOperationException))]
        public void a_stubbed_object_does_not_allow_its_virtual_properties_to_be_stubbed()
        {
            _stubbedObject.Stub(x => x.VirtualProperty).Return("test");
            Assert.AreNotEqual("test", _stubbedObject.VirtualProperty);
        }

You may have noticed that the test class has virtual and non-virtual members. If you use NHibernate, you are probably used to seeing virtual members. For a stubbed object, properties behave similarly (at least from the consumer’s POV) whether they are virtual or not.

Methods

Methods on a stubbed object behave as one would expect considering that a stub is a sort of proxy of your real object. Here we see that non-virtual methods on a stubbed object are actually executed while virtual methods are not:

        [Test]
        public void non_virtual_methods_on_a_Stubbed_object_are_exectued()
        {
            string testString = "test of method";

            _realObject.VirtualProperty = testString;
            _stubbedObject.VirtualProperty = testString;

            Assert.AreEqual(testString, _stubbedObject.DoSomething());
            Assert.AreEqual(testString, _realObject.DoSomething());
        }

        [Test]
        public void virtual_methods_on_a_Stubbed_object_are_not_executed()
        {
            string testString = "test of method";

            _realObject.VirtualProperty = testString;
            _stubbedObject.VirtualProperty = testString;
            
            Assert.AreEqual(null, _stubbedObject.DoSomethingVirtually());
            Assert.AreEqual(testString, _realObject.DoSomethingVirtually());
        }

For the next couple of tests, we’ll want to demonstrate how expectations work with a stubbed object when they are acted on by other classes. To do this, we’ll need another class to call methods on our stubbed object:

    public class StubObjectHelper
    {
        private readonly StubObject _stubObject;

        public StubObjectHelper(StubObject stubObject)
        {
            _stubObject = stubObject;
        }

        public void CallAMethodOnStubObject()
        {
            _stubObject.MethodThatShouldBeCalled();
        }
    }

First up, a stubbed object can assert that its methods were called:

        [Test]
        public void a_stubbed_object_can_assert_if_one_of_its_methods_was_called()
        {
            StubObjectHelper helper = new StubObjectHelper(_stubbedObject);

            helper.CallAMethodOnStubObject();
            _stubbedObject.AssertWasCalled(x => x.MethodThatShouldBeCalled());
        }

    }

However, a stubbed object cannot verify expectations set on its methods:

        [Test]
        public void a_stubbed_object_does_not_verify_expectations_set_on_its_methods()
        {
            //Oren (on stubs): "You can setup expectations on it, so it would act in certain ways, 
            // but those expectations will never be verified."

            StubObjectHelper helper = new StubObjectHelper(_stubbedObject);
            _stubbedObject.Expect(x => x.MethodThatShouldBeCalled());

            //the next line has no effect
            helper.CallAMethodOnStubObject();

            _stubbedObject.VerifyAllExpectations();

        }

This is one of the key areas where stubs differ from mocks. In the next article, we’ll examine the other subtle differences between the two.

Written by twisted

April 7th, 2009 at 9:38 pm

Mocking for Fun & Profit: Part 1 – Isolation

without comments

When creating unit tests in a project of any complexity, dependencies between objects can lead to major headaches when trying to setup expected conditions.  Even when the Law of Demeter is followed, dependency chains will abound.

Take the following trivial classes for example:

    public class ObjectBeingTested : ObjectForTesting
    {
        public ObjectBeingTested(DependentObjectA dependentObjectA)
        {
            DependentObject = dependentObjectA;
            ValidValue = 1;
        }
    }

    public class DependentObjectA : ObjectForTesting
    {
        public DependentObjectA(){}
        public DependentObjectA(DependentObjectB dependentObject)
        {
            DependentObject = dependentObject;
            ValidValue = 2;
        }
    }

    public class DependentObjectB : ObjectForTesting
    {
        public DependentObjectB(DependentObjectC dependentObject)
        {
            DependentObject = dependentObject;
            ValidValue = 3;
        }

    }

    public class DependentObjectC : ObjectForTesting
    {
        public DependentObjectC()
        {
            ValidValue = 4;
        }
    }

    public interface ITestableObject
    {
        bool IsValid();
    }

    public abstract class ObjectForTesting : ITestableObject
    {
        public ITestableObject DependentObject{ get; set;}
        protected int ValidValue { get; set; }
        public virtual int SomeValue { get; set; }

        public virtual bool IsValid()
        {
            return DependentObject == null || 
                (DependentObject.IsValid() && SomeValue == ValidValue);
        }
    }

To test ObjectBeingTested, we have to setup 3 other objects first.  Our test might look something like the following:

    [TestFixture]
    public class When_testing_an_Entity_with_a_chain_of_dependencies
    {
        private ObjectBeingTested _objectBeingTested;
        private DependentObjectA _a;
        private DependentObjectB _b;
        private DependentObjectC _c;

        [SetUp]
        public void SetUp()
        {
            _c = new DependentObjectC();
            _b = new DependentObjectB(_c);
            _a = new DependentObjectA(_b);
            _objectBeingTested = new ObjectBeingTested(_a);
        }

        [Test]
        public void all_dependencies_must_be_setup_prior_to_testing_the_logic_in_our_object_under_test()
        {
            _c.SomeValue = 4;
            _b.SomeValue = 3;
            _a.SomeValue = 2;
            _objectBeingTested.SomeValue = 1;

            Assert.IsTrue(_objectBeingTested.IsValid());
        }
    }

This looks more like an integration test than a unit test.

To add to this nightmare, imagine that we have tests on all our objects (with similar setups) and we then change the logic in DependentOjbectC. Now every test that touches DependentObjectC (or touches an object that touches DependentObjectC, and so on) has to be fixed even though nothing changed in the object that was being tested. Soon you’ll find yourself spending more time fixing up seemingly unrelated tests instead of adding value.

So, how do we accomplish unit testing in this sort of scenario:  MockingIsolation Frameworks.

See this excellent article on why I prefer to use the term “Isolation Framework” instead of “Mocking Framework”.  In short, “Mocking Framework” can be a bit intimidating.  What is a Mock?  How do I create one?  Another !@#$ framework to learn!?

There is already a substantial learning curve for TDD.  Throw in “Mocking” and it becomes a bit overwhelming.  It took me some time to wrap my head around the subject matter and I can only imagine that it would have been a lot easier to grasp the concepts if the name spoke more to the why than the what.

Enough preaching, let’s see how an isolation framework can clear up our tests and put the “unit” back into “unit testing”.  (Note: for these examples, I’ll be using RhinoMocks v3.5 and NUnit.)

    [TestFixture]
    public class When_testing_an_Entity_with_a_chain_of_dependencies_using_an_Isolation_Framework
    {
        private ObjectBeingTested _objectBeingTested;
        private DependentObjectA _immediateFriend;

        [SetUp]
        public void SetUp()
        {
            _immediateFriend = MockRepository.GenerateStub<DependentObjectA>();
            _objectBeingTested = new ObjectBeingTested(_immediateFriend);
        }

        [Test]
        public void the_behavior_of_our_object_under_test_can_be_isolated_from_the_behavior_of_its_dependency_chain()
        {
            _immediateFriend.Stub(x => x.IsValid()).Return(true);

            _objectBeingTested.SomeValue = 1;
            
            Assert.IsTrue(_objectBeingTested.IsValid());
        }
    }

Notice that we only had to create a single stub for our object’s immediate dependency.  This has the following benefits:

  • We can truly isolate and test the behavior of our object.  Now we know that if our tests fail, its because of an issue in this specific class
  • Tests look cleaner
  • No more green-red-green whack-a-mole when changing objects that do not have immediate relationships.
  • Tests are faster to write since the logic of dependent objects no longer has to be examined to determine the proper setup

The remaining articles in this series will be focusing on specific functionality in RhinoMocks v3.5. For now, here’s a list of the links mentioned in this article for further reading:

Written by twisted

January 30th, 2009 at 9:51 pm