in·dom·i·ta·ble
adj.   Incapable of being overcome, subdued, or vanquished; unconquerable.

8th
APR

Javascript for Grown-Ups: Setting up the DOM

Posted by indomitablehef | Filed under jQuery, qUnit, TDD

When testing javascript and jQuery code, I find I’m often adding elements here and there to the DOM, usually appending to a div. In such cases, I try to write my functions such that I pass in the container div as a selector. For example:

 
function AddToyToBox(toy, box) {
    var toyId = toy.Name.replace(/ /g, ''); //remove spaces from the name
    $('<div id="' + toyId + '"></div>').addClass('toy').appendTo(box);
}

In this trivial example, we’re taking a “toy” object, creating a div for it, and adding it to some element in the DOM that represents a “box”, probably another div.

The qUnit test for this method, then, looks like this: (using my custom Assertions, described here)

 
test("Can Add Toy to ToyBox", function() {
    var toy = new Toy('Monster Truck');
    var expectedToyBoxHtml = "<div class=\"toy\" id=\"MonsterTruck\"></div>";
    AddToyToBox(toy, '#stubToyBoxDiv');
    Assert.AreEqual(expectedToyBoxHtml, $('#stubToyBoxDiv').html());
});

Notice the reference to #stubToyBoxDiv. In my tests.html file, I was putting some “stub” html at into a div at the bottom of the file, so that I would have a container to drop my elements into when testing methods like AddToToBox(). I even had a clever way to clean up after myself after I was done - I made my last test remove the div that contained all my stub container divs. This quickly became a pain, however, because I found myself needing to have #stubToyBoxDiv1, #stubToyBoxDiv2, etc.

But thanks to jQuery, there is a much better and more elegant way to do this than littering up your tests.html file with stub divs. Instead, just create the dom element you need as part of your test setup, and remove it when you’re done:

test("Can Add Toy to ToyBox", function() {
    var toy = new Toy('Monster Truck');
     var expectedToyBoxHtml = "<div class=\"toy\" id=\"MonsterTruck\"></div>";
 
    $('<div id="stubToyBoxDiv"/>').appendTo('body');
 
    AddToyToBox(toy, '#stubToyBoxDiv');
 
    Assert.AreEqual(expectedToyBoxHtml, $('#stubToyBoxDiv').html());
 
    $('#stubToyBoxDiv').remove();
});

I added the following DOMSetup and DOMTeardown methods, for better test readability:

DOMSetup = function(element, container) {
    var el = $(element);
    if (container != null)
        el.appendTo(container);
    else
        el.appendTo('body');
}
 
DOMTearDown = function(selector) {
    $(selector).remove();
}

So now my test can look like this:

test("Can Add Toy to ToyBox", function() {
    var toy = new Toy('Monster Truck');
    var expectedToyBoxHtml = "<div id=\"MonsterTruck\" class=\"toy\"></div>";
 
    DOMSetup('<div id="stubToyBoxDiv"/>');
 
    AddToyToBox(toy, '#stubToyBoxDiv');
 
    Assert.AreEqual(expectedToyBoxHtml, $('#stubToyBoxDiv').html());
 
    DOMTearDown('#stubToyBoxDiv');
});

7th
APR

Javascript for Grown-Ups: an Assertion Helper for qUnit

Posted by indomitablehef | Filed under jQuery, qUnit, TDD

In an effort to write my jQuery and Javascript code with the same rigor I use when writing my c# and even Sql code, I’ve started using the qUnit testing framework. qUnit is the unit testrunner for the jQuery project.

So far, I’m loving it, with a only few caveats. For one, I would like to write more BDD-style tests, and though I can sort of do it, it’s not very expressive. At some point, I’m going to want to try out JSpec, but for now I’m going to keep on working with qUnit.

Antother issue is that I don’t find it very expressive. For example, the AssertAreEqual function is called just “equals(actual, expected)”, and the AssertIsTrue method is just “ok(actual, expected)”. I miss my Assert.AreEqual and Asssert.IsTrue expressiveness, and I don’t like having “actual” come before “expected” in the parameter list.

So, I wrote this little AssertionHelper to help make my tests more expressive:

function AssertionHelper() {
 
    this.IsTrue = function(bool, message) {
        ok(bool,message);
    };
 
    this.IsFalse = function(bool, message) {
        ok(!bool,message);
    };
 
    this.AreEqual = function(expected, actual, message) {
        equals(actual, expected, message);
    };
 
    this.AreNotEqual = function(expected, actual, message) {
        ok(actual != expected, message);
    };
 
    this.AreSame = function(expected, actual, message) {
        same(actual, expected, message);
    }
}

Now, in my tests.js file, I can just declare a variable called Assert as a new AssertionHelper, and use it in my tests to get the familiar expressiveness and semantics of the xUnit family of testing frameworks.

 
var Assert = new AssertionHelper();
 
$(document).ready(function() {
 
    test("a basic test example", function() {
 
        // instead of:
        ok(true, "this test is fine");
 
        //use
        Assert.IsTrue(true);
        Assert.IsTrue(true, "this test is fine");
        Assert.IsFalse(false);
        Assert.IsFalse(false, "this test is fine");
 
        var value = "hello";
        //instead of:
        equals("hello", value, "We expect value to be hello");
 
        //use
        Assert.AreEqual(value, "hello");
        Assert.AreEqual(value, "hello", "We expect value to be hello");
 
        Assert.AreNotEqual(value, "goodbye");
        Assert.AreNotEqual(value, "goodbye", "We expect value to be hello");
 
        Assert.AreNotEqual(value, "hello");
        Assert.AreNotEqual(value, "hello", "this test and the one before it should fail");
 
        var x = { "name": "myobject" };
        var y = x;
        var z = { "name": "myobject2" };
 
        Assert.AreSame(y, x);
        Assert.AreSame(y, x, "these two should be the same");
 
        Assert.AreSame(z, x, "this test should fail");
 
 
    });
 
});

UPDATE: Reader ToneD shared the following improvement in the comments. He’s using a static class, which negates the need for instantiation and gives you intellisense on the Assert methods:

Assert = {
            IsTrue: function(bool, message) {
                ok(bool, message);
            },
 
            IsFalse: function(bool, message) {
                ok(!bool, message);
            },
 
            AreEqual: function(expected, actual, message) {
                equals(actual, expected, message);
            },
 
            AreNotEqual: function(expected, actual, message) {
                ok(actual != expected, message);
            },
 
            AreSame: function(expected, actual, message) {
                same(actual, expected, message);
            }
        }

25th
MAR

Exploring MvcContrib: TestControllerBuilder

Posted by indomitablehef | Filed under Asp.Net MVC, TDD

The MvcContrib project on codeplex is “a series of assemblies that add functionality to Microsoft’s ASP.NET MVC Framework and make the framework easier to use”. One of the areas I’ve found immediately useful is the TestHelper library.

Let’s take a deeper look into this library, starting with the TestControllerBuilder.

One of the many things that the Asp.Net Mvc Framework has going for it is that it is easier to test. Even so, when you’re dealing with HttpContext, Request, Response, Form, QueryString and such, it can still be very difficult to isolate all the things you need isolate, mock all the things you need to mock, and get access to internal collections like Form, QueryString, and Session. The TestControllerBuilder gives us a test-specific ControllerFactory that we can use to initialize our controllers for testing, and gives us access to those internal collections.

To set up our “PatientController” for testing using the TestControllerBuilder, we create a PatientController and a TestControllerBuilder and call “InitializeController”, like this:

 
    [TestFixture]
    public class PatientControllerTest
    {
    	private PatientController controller;
    	private TestControllerBuilder controllerBuilder;
 
    	[SetUp]
    	public void Setup()
    	{
    		controller = new PatientController();	
	        controllerBuilder = new TestControllerBuilder();
    		controllerBuilder.InitializeController(controller);
	}
<...>

Imagine that we are storing some data about the current state of this Patient in the Session - for example, “Admitted”, “Triage”, “ER”, etc. And imagine that we are grabbing that state information from the Form collection directly. (There are certainly many better ways to do this, but bear with me for the sake of this contrived example). We need to test to make sure that when the state is passed in as a Form variable, after the controller action is completed, the Session variable for PatientState is set properly.

Having set up our controller using the TestControllerBuilder, we can now write a test like this:

 
    [Test]
    public void PatientStateInFormVariableShouldSetPatientStateInSessionVariable()
    {
          controllerBuilder.Form["PatientState"] = "Admitted";
          controller.SetState();
	  controller.HttpContext.Session["PatientState"].ShouldEqual("Admitted", "");
    }

Pretty good test, right? But it looks a little too much like magic for me to just copy and paste it and move on, so let’s dig into how the TestControllerBuilder does this magic.

Notice that the Form collection we added to was the controllerBuilder.Form collection, and that the HttpContext we checked for our session variable was controller.HttpContext. Obviously this isn’t a real HttpContext, so let’s see where it comes from. If we pull down the source code for MvcContrib and look at the TestControllerBuilder.cs class in the MvcContrib.TestHelper project, it becomes much clearer.

The TestControllerBuilder has public properties for HttpContext, Session, and Form, like so:

<...>
		/// <summary>
		/// Gets the HttpContext that built controllers will have set internally when created with InitializeController
		/// </summary>
		/// <value>The HTTPContext</value>
		public HttpContextBase HttpContext { get; protected set; }
<...>
		/// <summary>
		/// Gets the Form data that built controllers will have set internally when created with InitializeController
		/// </summary>
		/// <value>The NameValueCollection Form</value>
		public NameValueCollection Form { get; protected set; }
<...>
		/// <summary>
		/// Gets the Session that built controllers will have set internally when created with InitializeController
		/// </summary>
		/// <value>The IHttpSessionState Session</value>
		public HttpSessionStateBase Session { get; protected set; }
 
<...>

The Constructor for TestControllerBuilder calls a protected method called SetupHttpContext, which creates mock objects for the HttpContext, Request, Response and Server objects, like so:

protected void SetupHttpContext()
{
	HttpContext = _mocks.DynamicMock<HttpContextBase>();
	var request = _mocks.DynamicMock<HttpRequestBase>();
	var response = _mocks.DynamicMock<HttpResponseBase>();
	var server = _mocks.DynamicMock<HttpServerUtilityBase>();
 
	_cache = HttpRuntime.Cache;
	SetupResult.For(HttpContext.Request).Return(request);
	SetupResult.For(HttpContext.Response).Return(response);
	SetupResult.For(HttpContext.Session).Return(Session);
	SetupResult.For(HttpContext.Server).Return(server);
	SetupResult.For(HttpContext.Cache).Return(_cache);
 
	QueryString = new NameValueCollection();
	SetupResult.For(request.QueryString).Return(QueryString);
 
	Form = new NameValueCollection();
	SetupResult.For(request.Form).Return(Form);

Notice that the public property HttpContext is a mock object, and the result of requesting HttpContext.Request is set up so that it will return a mocked HttpRequestBase object as well. Notice also that we’ve setup the result for calls to HttpContext.Session to return the TestControllerBuilder’s public Session property.

Taking it to the next step down, we see that calling HttpContext.Request.Form will return the public property Form, which is just a NameValueCollection. It’s worth noting again here that the Form, QueryString, and Session objects we will get from our mocked HttpContext object are not mock objects but “stubbed” objects - public properties of the TestControllerBuilder class.

Now, to wire these mocked and stubbed objects up so that our controller can use them when we are testing it, we call the TestControllerBuilder’s InitializeController method, and pass it our controller. InitializeController looks like this:

/// <summary>
/// Creates the controller with proper environment variables setup. 
/// </summary>
/// <param name="controller">The controller to initialize</param>
public void InitializeController(Controller controller)
{
	var controllerContext = new ControllerContext(HttpContext, RouteData, controller);
	controller.ControllerContext = controllerContext;
	controller.TempData = TempDataDictionary;
}

Here we create a new ControllerContext, and pass in the Mocked-up and Stubbed-up HttpContext object that was set up by the constructor call to SetUpHttpContext(), and set the controllerContext on our controller to that new ControllerContext.

So, when we set the form variable:

          controllerBuilder.Form["PatientState"] = "Admitted";

…and our controller’s SetState() method calls some code that looks something like this:

	  Session["PatientState"] = Request.Form["PatientState"];

… When our controller attempts to access the value at Request.Form, the Form object it is getting is the NameValueCollection property called “Form” from the TestControllerBuilder that was used to initialize the ControllerContext for our controller.

Here is the relevant code from the TestControllerBuilder’s protected SetUpHttpContext method:

 
	HttpContext = _mocks.DynamicMock<HttpContextBase>();
	var request = _mocks.DynamicMock<HttpRequestBase>();
<...>
	SetupResult.For(HttpContext.Request).Return(request);
<...>
	Form = new NameValueCollection();
	SetupResult.For(request.Form).Return(Form);

In our test, when we call:

	  controller.HttpContext.Session["PatientState"].ShouldEqual("Admitted", "");

The session collection we are getting is the public HttpSessionStateBase property of the TestControllerBuilder called “Session”, which was set up to be the result of any calls to HttpContext.Session in our mocked HttpContext.

So, that’s the TestControllerBuilder - an easy way to test your controllers and get access to stubs of all those internal collections based on HttpContext that you could never get to in order to test before. Next time, we’ll take a look at the TestHelper project’s extension methods that allow you to examine the return values of your controller actions, and what parameters were passed to ReturnView, RedirectToAction, etc.

6th
FEB

Forms Authentication in Asp.Net MVC

Posted by indomitablehef | Filed under Asp.Net MVC, TDD

This is part 1 of 4
Forms Authentication in Asp.Net MVC

I’ve been working on a testable solution for my Asp.Net MVC project. I have a solution that I think works, but I’d love to hear comments/criticisms if you’ve got any.

First, set up forms authentication in web.config:

    <authentication mode="Forms">
      <forms loginUrl="Membership/Login" defaultUrl="/" />
    </authentication>

Now you’ll need an interface for IAuthenticationProvider

1
2
3
4
5
 public interface IAuthenticationProvider
    {
        bool IsAuthenticated(ControllerContext context);
        void RedirectToLogin(ControllerContext context);
    }

And an implementation, FormsAuthenticationProvider

1
2
3
4
5
6
7
8
9
10
11
12
public class FormsAuthenticationProvider: IAuthenticationProvider
    {
        public virtual bool IsAuthenticated(ControllerContext context)
        {
            return context.HttpContext.User.Identity.IsAuthenticated;
        }
 
        public virtual void RedirectToLogin(ControllerContext context)
        {
            context.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + string.Format("?ReturnUrl={0}", context.HttpContext.Request.Url.AbsolutePath), true);
        }
    }

I’m doing authentication on Controllers using an ActionFilterAttribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
     public class RequiresAuthenticationAttribute : ActionFilterAttribute
    {
        private IAuthenticationProvider authenticationProvider;
 
        public RequiresAuthenticationAttribute(IAuthenticationProvider provider) {
            authenticationProvider = provider;    
        }
 
        public RequiresAuthenticationAttribute() : this(ServiceLocator.Current.GetInstance<IAuthenticationProvider>()) {}
 
 
 
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!authenticationProvider.IsAuthenticated(filterContext)) {
                authenticationProvider.RedirectToLogin(filterContext);
            }
        }
    }

A couple of things to notice about this:

I have a test-specific constructor, that allows me to pass in the IAuthentication provider. I’m using Castle Windsor as an IoC container, and the LocatorProvider for ServiceLocator. In my parameter-less constructor, I simply get the configured IAuthenticationProvider from the IoC container.

To use my RequiresAuthentication attribute, I just decorate the controller with it, like this

1
2
3
4
5
6
7
8
    [HandleError]
    [RequiresAuthentication]
    public class HomeController : Controller
    {
        public ActionResult Index() {
            return View();
        }
    }

Now for my tests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[TestFixture]
    public class RequiresAuthenticationAttributeTests
    {
        [Test]
        public void CanRedirectToLoginWhenNotAuthenticated() {
 
            //arrange
            var mockedProvider = MockRepository.GenerateMock<IAuthenticationProvider>();
            mockedProvider.Expect(x => x.IsAuthenticated(null)).IgnoreArguments().Return(false);
            mockedProvider.Expect(x => x.RedirectToLogin(null)).IgnoreArguments();
            //act 
            var attribute = new RequiresAuthenticationAttribute(mockedProvider);
            attribute.OnActionExecuting(null);
            //assert
            mockedProvider.VerifyAllExpectations();
        }
 
        [Test]
        public void CanPassThroughWhenAuthenticated()
        {
            //arrange
            var mockedProvider = MockRepository.GenerateMock<IAuthenticationProvider>();
            mockedProvider.Expect(x => x.IsAuthenticated(null)).IgnoreArguments().Return(true);
            //act 
            var attribute = new RequiresAuthenticationAttribute(mockedProvider);
            attribute.OnActionExecuting(null);
            //assert
            mockedProvider.AssertWasNotCalled(x => x.RedirectToLogin(null));
            mockedProvider.VerifyAllExpectations();
        }
 
    }

Using Rhino Mocks, I just mock the IAuthenticationProvider and pass it in to the constructor of my RequiresAuthenticationAttribute.

The code inside the FormsAuthenticationProvider relies on httpContext, which is damn near impossible to mock…I tried. So with this solution, I’ve at least isolated that code so that I can test everything else. I would LOVE to hear your thoughts on this…be brutal.

Update: The authentication section of Web.config indicates that the loginurl is Membership/Login….that means you’ll need a MembershipController with a Login action to display the login view, like this

1
2
3
4
5
6
7
public class MembershipController: Controller
    {
        public ActionResult Login()
        {
            return View("Login");
        }
    }

Update: continue on to Part II, where we dig into the MembershipController

2nd
JAN

SqlTdd: TestSuiteSetup/Teardown and TestSetup/Teardown

Posted by indomitablehef | Filed under TDD

The SqlTdd project now has TestFixtureMethods.

14th
DEC

The Motivation Behind SqlTdd

Posted by indomitablehef | Filed under SqlTdd, TDD

We software developers have a tendency to turn our noses up at SQL “code”. When we get excited about good design, good sql design is rarely part of the discussion. Likewise, when we talk about Testability, the goal is often to eliminate the database from what we’re testing entirely. I’m all for that, actually, but it’s not the whole story. The reality is that SQL Stored Procedures, functions, and other programming constructs is often the “right place” to implement some piece of functionality. Even when the argument can be made that it’s not, sometimes that’s where it ends up anyway. Sometimes, that’s the skillset you have available, so that what you do. It’s “the hammer” antipattern:

When all you have is a hammer, everything looks like a nail.

But calling it an anti-pattern isn’t enough. There’s a lot of working code out there, written entirely in SQL. There are a lot of capable SQL developers out there, and they’re mostly being ignored by the part of the industry that cares about testabilty, agility, and refactoring.

SqlTdd isn’t the first unit testing framework for SQL Server, but it’s my attempt to build a better one. Here are some of my design goals

  1. A capable SQL devloper should be able to use it without ever needing to leave SQL Server Management Studio - i.e., entirely in SQL, as far as he’s concerned
  2. It should lend itself well to the use of “Tests as Documentation”, and generally more readable SQL Code
  3. It should integrate well with existing automated build and continuous integration tools used in traditional Test Driven Development
  4. It should enable sophisticated testing techniques, such as custom assertions, transaction rollback teardown, Test Suites, setup/teardown, and even mocks and stubs.

20th
SEP

Hillbilly Soul-Searching

Posted by indomitablehef | Filed under TDD

I always appreciate Kyle’s honesty and transparency. Read his response to Roy Osherove’s controversial post: Do the right thing. Assuming you know what that is.

19th
SEP

No more short cuts, god classes or big balls of mud

Posted by indomitablehef | Filed under TDD

Jimmy Bogard on the lifestyle change that is TDD: TDD design trade-offs and junk food

Starting TDD is giving up OO junk food. No more short cuts, god classes or big balls of mud, which seemed so comforting before. No more wallowing in the debugger, taking pride in knowing how to take apart the Gordian knot, or making a mental stack of variables. It hurt at first, seemed a little alien, but led toward leaner, tighter and more cohesive designs.

17th
SEP

SQL TDD

Posted by indomitablehef | Filed under TDD

So, it’s been awhile, but here we go again. It’s been a busy summer for me, what with the birth of my daughter, Cecilia. I’ve also been learning a lot, and wishing I had the time to blog about the stuff I’ve been learning. So here goes…

The company I work for does a lot of things, but our bread and butter is data warehousing. This means that we have lots of solutions that are nearly 100% database-centric. There’s a lot of code in stored procedures, and a lot of data moving around. Much of the code is used for data scrubbing, business rule implementation, etc. In our migration towards agile, we’re doing Agile Database development. Automated builds, version control, continuous integration, the whole nine yards. That includes TDD. How? Well, to start, we used tSQLUnit, and added onto it. That worked, but I decided that we needed more. When I couldn’t find anything better, I decided to write my own. It should be ready sometime this fall, but I’m going to go ahead and start sharing it here. My intent is for it to be open-source, and maybe I’ll write some tools to go with it…we’ll see.

To start, I wanted a framework that reported its test failures by raising an exception, not just by dropping a record into a “test result” table. So first, let’s examine how we’re going to get our tests to fail. We’ll need a specific error message

1
2
3
4
EXECUTE sp_addmessage 50100, -- Message id number.
        17, -- Severity.
        N'Assert Failed. %s';
    GO

This next decision is up for debate (as is everything about this, really…please send me any feedback you have, I’d appreciate the input). Readability is important to me, and the use of “tests as documentation”. I normally shy away from over-use of different schemas in my database development, preferring to just stick everything in dbo. But for this case, I decided to create a special schema called “Assert”. This schema will, naturally, hold all my Assert procedures.

1
CREATE SCHEMA Assert

Now we’ll create our Assert.Fail procedure, and raise the error we added earlier:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
CREATE PROCEDURE [Assert].[Fail]
    @expected SQL_VARIANT,
    @actual SQL_VARIANT,
    @message NVARCHAR(1000) = '',
    @location NVARCHAR(1000) = ''
AS 
    DECLARE @failureString  NVARCHAR(1000),
			@messageString  NVARCHAR(1000), 
			@locationString NVARCHAR(1000)
 
    SELECT @messageString = CASE WHEN LEN(@message) > 0 THEN 
							' Messsage: [' + @message + ']' 
							ELSE '' END 
 
    SELECT @locationString = CASE WHEN LEN(@location) > 0 THEN 
							' Location: [' + @location + ']' 
							ELSE '' END 
 
    SET @failureString = ' Expected: [' + CONVERT(NVARCHAR, @expected) 
                       + '], Actual: [' + CONVERT(NVARCHAR, @actual) + '].' 
                       + @messageString + @locationString
 
    RAISERROR (50100,17,71,@failureString)

Some things to notice here

  1. I’m using SQL_VARIANT- I want to be able to pass in any data type to this “Fail” procedure for @expected and @actual. This, of course, constrains me to SQL2005 and higher, but I was already planning on that.
  2. I’m using NVARCHAR - In some of my earlier runs at this, I experimented with using an extended stored procedure as the test running. I may still go that route…not sure. In doing that, I found that to I had to use NVARCHAR in some places. At the time, I started using it everywhere. I’m not 100% sure I want to continue this, but there it is, for now.
  3. I’m passing in @location - I intend this to be used to pass in the name of the calling stored procedure (a test). Usually, this parameter will be supplied with the value
    OBJECT_NAME(@@PROCID) - i.e., the name of the calling stored procedure, like so:
1
2
3
4
5
6
7
8
CREATE PROCEDURE MyTestMethod
AS 
	DECLARE @location sysname
	SET @location =  OBJECT_NAME(@@PROCID)
 
	EXEC Assert.Fail @expected = 1, @actual = 2, 
                               @message = N'expected count does not match', 
                               @location = @location

If I had some way of looking up the call stack, to see which stored procedure called Assert.Fail, I wouldn’t need to do this, but as yet I haven’t found any way to do this. When you execute MyTestMethod, you get

1
2
Msg 50100, Level 17, State 71, Procedure Fail, Line 24
Assert Failed. Expected: [1], Actual: [2]. Messsage: [expected count does NOT match] Location: [MyTestMethod]

Of course, it wouldn’t be proper to write a testing framework without using TDD to write it, so here’s what our first self-test looks like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
CREATE PROCEDURE [dbo].[Assert_Fail_Base]
AS
 DECLARE @failMessage NVARCHAR(4000)
 BEGIN TRY
	EXEC Assert.Fail 0,1
    RAISERROR ('Assert.Fail did not raise execption at all.' ,16,72)
 END TRY
 BEGIN CATCH
    DECLARE @number INT, @severity INT, @message NVARCHAR(4000)
    SELECT @number = ERROR_NUMBER(),
		   @severity = ERROR_SEVERITY(),
           @message = ERROR_MESSAGE()
 
    -- is the error number correct 
    IF @number <> 50100
    BEGIN
      SET @failMessage = 'Assert.Fail did not raise assertion exception as expected. Instead, it raised [' + @message + ']'
      RAISERROR (@failMessage ,16,71)
    END
 END CATCH

7th
APR

Unity

Posted by indomitablehef | Filed under .Net, TDD

The Unity DI (Dependency Injection) container from the Microsoft Patterns and Practices team shipped over the weekend. Download it here, and check out these screen casts on using it.