By default objects mocked using MOQ will handle calls to method/properties that have not been defined, which 99% of the time will be the desired behaviour. Occasionally however a situation will require that MOQ throws an exception when accessing an undefined method or property. The MOQ framework provides this functionality via the MockBehavior enum but this can only be set during the construction of the mocked object. Typically this won’t cause any problems as the mocked objects are created inline but we’ve just encountered a scenario that needed a little lateral thinking as for reusability we have objects that inherit from Mock<>. These mocked objects already had constructor parameters which (in the short term) we didn’t wish to change so to get around this we created a static property on the mocked object that is then used to inject into the base MOQ constructor.
public class MockHttpContext : Mock<HttpContextBase> { static MockHttpContext() { MockBehavior = MockBehavior.Default; } public static MockBehavior MockBehavior { get; set; } public MockHttpContext(bool shareCommonHttpCookieCollection = true) : base(MockBehavior) { … } … }
Note: Being a static property it does mean that we have to remember to reset the value after constructing the instance in question, but in the short term it did resolve the issue of how to change the MockBehaviour without modifying the mocked objects constructor.
Today I realised that I’d forgotten how spoilt I am using Resharper and dotCover to run my unit tests. Put another way I’d forgotten how badly Visual Studio plays with any other unit test frameworks other than MS Test! I’m used to and really like the fluent API style of NUnit’s Assert.That(…) syntax so having to fall back to MS Test always feels like a step back. If you ever find yourself in a situation . . .
When I first started looking into Windows Workflow one of the first things that I liked about it was how it separated responsibilities. The workflow was responsible for handling the procedural logic with all its conditional statements, etc. Whilst individual code activities could be written to handle the business logic processing; created in small easily re-usable components. To try and realise my original perception this series of blog posts will cover the unit testing of . . .