Unit Testing with DataAnnotations outside of MVC

This past week has seen us start on a big project at work to re-architect the site into .net and MVC2.  Naturally we have our models in a separate project, and we have two separate test projects (Unit and Integration) setup to use NUnit.

As it’s early days for us, and our first “real” MVC project I thought I’d write this up, a) as an aid to learning for me, but b) to try to gain feedback from the community on what they do with regards validation on their models.

I can see a few different ways we could have done this (annotate the ViewModels we’ll use on the front end, build in logic into our setters to validate, etc. etc.) but we’re now going down a route that so far feels ok.  That said, we’re focussing solidly on the modelling of our business logic at present, so haven’t yet brought the model “out to play” as it were.

Hopefully the above gives a wee bit of insight into where we are with it.

We’ve decided to plump for the MetaData model approach to keep the main objects slightly cleaner – an example for us would be:

namespace MyCompany.Models.Entities
{
	/// 
	/// 
	/// 
	[MetadataType(typeof(MyCompanyUserMetaData))]
	public class MyCompanyUser
	{
		public int UserId { get; set; }

		public string Username { get; private set; }
		...

		public void SetUsername(string newUsername)
		{
			if (Username != null)
				throw new ArgumentException("You cannot update your username once set");

			//TODO: where do we ensure that a username doesn't already exist?
			Username = newUsername;
		}
	}
}

and then in a separate class:

namespace MyCompany.Models.Entities
{
	public class MyCompanyUserMetaData
	{
		[Required(ErrorMessage="Your password must be between 6 and 20 characters.")]
		[StringMinimumLength(6, ErrorMessage="Your password must be at least 6.")]
		public string Password { get; set; }

		[Required(ErrorMessage="Your username must be between 6 and 20 characters.")]
		[StringLength(20, MinimumLength=6, ErrorMessage="Your username must be between 6 and 20 characters.")]
		[MyCompanyUserUsernameDoesNotStartWithCM(ErrorMessage="You cannot use the prefix 'CM-' as part of your username")]
		[CaseInsensitiveRegularExpression(@"^[\w\-!_.]{1}[\w\-!_.\s]{4,18}[\w\-!_.]{1}$", ErrorMessage = "Your username must be between 6 and 20 characters and can only contain letters, numbers and - ! _ . punctuation characters")]
		public string Username {get;set;}
	}
}

With all of this in place you’re all well and good for the MVC world, though unit testing just doesn’t care about your Annotations so your simple unit tests:

		
[Test]
public void SetUsername_UsernameTooShort_ShouldThrowExceptionAndNotSetUsername()
{
	// Arrange
	testUser = new MyCompanyUser();
			
	// Act

	// Assert
	Assert.Throws(() => testUser.SetUsername("12345")); // length = 5
	Assert.That(testUser.Username, Is.Null, "Invalid Username: Username is not null");
}

won’t give you the expected results as the logic of that is based upon the DataAnnotation.

What was our solution?

After much reading around (there didn’t seem to be an awful lot out there covering this) we took a two step approach.  First was to allow SetUsername to validate against the DataAnnotations like so:

		
public void SetUsername(string newUsername)
{
	if (Username != null)
		throw new ArgumentException("You cannot update your username once set");

	Validator.ValidateProperty(newUsername, new ValidationContext(this, null, null) { MemberName = "Username" });

	//TODO: where do we ensure that a username doesn't already exist?
	Username = newUsername;
}

Validator is well documented and there are a few examples out there of people doing this within their setters.  Essentially validating the input for a particular MemberName (Username in this case).

The second step was necessary because of the approach we’d taken with the MetaData class above, and it was a mapping in the TestFixtureSetup within our unit tests:

TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(MyCompanyUser), typeof(MyCompanyUserMetaData)), typeof(MyCompanyUser));

This line (though I’ve yet to look down at the source code level) would appear to just be a standard mapping for the class to tell it where to find the metadata/annotations.

After putting those two things in place, the unit tests successfully validate against the annotations as well as any coded business logic, so jobs a good un!

Was it the right solution?

This is where I ask you, the person daft enough to suffer this blog post!  I have no idea if there is a better way to do this or how this will pan out as we propagate up to the MVC level – will I be causing us headaches taking this approach, will it simply not work because of overlap between the way MVC model binder validates versus what we’ve done down at the domain level?

It’s still early days for the project, and the above feels like a nice way to validate down at a business domain level, but how it pans out as we propagate wider and start letting other projects consume, hydrate and update the models… well that’s anyone’s guess!

Comments very much welcome on this one folks 🙂

NerdDinner, and initial thoughts on MVC

Although I’ve not yet finished it, I thought I’d start my wee reflection on MVC as learned through NerdDinner.

Obviously, the immediate thing that hits you is that you aint in Kansas any more – ignore the asp.net postback model, it’s all change and there is going to be some significant re-learn before I get anywhere near good I think.

I do love the separation of concerns, the theory behind it is sound from a maintenance and extensibility point of view.  Keeping my model tucked away nicely, and using it to provide the meat that the controller feeds of, which then in turn drives the View I think makes perfect sense.  I need to work far more heavily on the URL Routing before starting to design anything bigger just to see how a richer navigation hierarchy will sit.

I love the way postbacks are handled (at least in the NerdDinner app) and AcceptVerbs() just makes sense to me.  I can see I’m going to have to read up a bit more on programming against an interface, as I haven’t covered so much of this.  I wasn’t a big fan of the Respository pattern, I’d have perhaps gone down the facade route, or (when and if I understand it) perhaps IoC will help with this, though obviously this was just one example.

It’s my first successful play with Linq to SQL, and I’m liking the abstraction and the codified approach to it, though I’ll have to run some heavier tests through SQL Profiler to see how it works in terms of performance.

I’m going to have to look through the source code to find out just how all of the helper methods work rather than just use them – chucking Html.ActionLink() on the page is all well and good, but I want to know what it actually does in the code (easily enough done now that MVC source code is available)

I’m only just getting now to the integration/work with Ajax, which I think will be interesting – I shall keep the blog updated with stuff as I cover it.

The weight lifts, back to the fun stuff…

Well, the launch of the bulk of the client sites we were working on throughout May/June has left me with a weeks holiday – yay!  I’m more determined than ever to spend it learning – busman’s holiday I guess, though I’d feel like I’d wasted the week if I sat playing on the consoles or just bumming around – I’m sure catching up on sleep will help too.

I’m really enjoying the learning that I can get from just an hour of reading through stackoverflow or those peoples tweets that I follow, key over the next week is focussing this and getting some more technical contacts to learn from – there are some cracking recent ones including @spolsky, @elijahmanor, and @scottgu – and just getting time to read all about it will be bliss.

I finally asked my first question on stackoverflow the other week and thankfully it was well received.  Polymorphism in c# has always for me been a timtowdi concept, and although I’ve not had significant need for it in the past, I’ve always liked the flexibility interfaces give in implementation.  Thankfully the answers seemed to back that up, and give some good concrete examples.  So nice to know there is a community around like this that will happily offer support/views, and ultimately can lead to a ‘best practice’ guide on issues.  Of course, we’ll ignore the ‘answering without reading the question’, and all the other minor issues SO has – on the whole, a cracking resource.

So, fingers crossed this will again be the start of regular posting – this next week is working through the MCTS training kit and just learning more, doing more – key areas I have to focus on really are build management (NANT), WPF (for MCTS and curiosity more than anything), Design Patterns (I’ve only really used the Facade in anger, but there is so much discussion at present about IoC and Dependency Injection that I have to have a read).

I want to be playing with Linq (the elements I’ve played with so far highlight how seriously powerful it is if used carefully) and other more ‘hands on’ elements, though I think getting that grounding right is first and foremost.

More to follow during this weeks ‘holiday’ 🙂