Author Archives: Mats Karlsson

Testable object wrapper

Have started experimenting with a way of wrapping the ‘system under test’ in a wrapper-class that also contains the mocked dependencies. The class is instantiated the same way as Brad Wilson’s Testable Object Pattern with a static Create method.

The big difference from his pattern is that the system under test is a public Sut-property instead of using inheritance. The Create method instanciates mocks for the dependencies and creates the system under test with reflection, so less boilerplate code for you to write.

The problem I have with inheritance here is that you kind of pollute your class you wish to test with other stuff. And what I like about putting the system under test as property is you can add fluent methods to your wrapper class making the tests easier to read and understand.

For example:

            const string userName = "Mats";
            const string emailAddress = "";
            var userRepository = new Mock<IUserRepository>();
            var mailer = new Mock<IMailer>();
            var user = new Mock<IUser>();

            user.Setup(m => m.EmailAddress).Returns(emailAddress);
            userRepository.Setup(m => m.Get(userName)).Returns(() => user.Object);

            var sut = new ResetPassword(userRepository.Object, mailer.Object);


            userRepository.Verify(d => d.Get(userName));
            mailer.Verify(d => d.SendMail(emailAddress));

Arrange is a bit noisy, and it’s not easy to see that the mock for user is not something the SUT is depending on, ResetPassword-class only depends on IUserRepository and IMailer.

Using the generic Testable object wrapper-class (called Tester) you then easily implement a wrapper with:

    public class ResetPasswordTester :
        Tester<ResetPasswordTester, ResetPassword, IUserRepository, IMailer>
        public Mock<IUserRepository> UserRepository { get { return Param1; } }
        public Mock<IMailer> Mailer { get { return Param2; } }

        public ResetPasswordTester WithUser(string userName, string emailAddress)
            var user = new Mock<IUser>();
            user.Setup(m => m.EmailAddress).Returns(emailAddress);

            UserRepository.Setup(m => m.Get(userName)).Returns(() => user.Object);
            return this;

The generic parameters are: the class itself (so Create-method returns correct instance), System under test (ResetPassword)  and one or more dependencies (IUserRepository, IMailer).

First dependency is first parameter, second dependency is second parameter. Tester automatically creates a instance of the system under test as a “Sut”-property.

Also added a fluent method (.WithUser(…) )that all tests for ResetPassword could use.

This gives you very clean and readable tests.

Another great effect is that if your class takes another dependency then you only have to change the signature of the wrapper and all tests using that wrapper work without any modification to the tests.

The first example could be refactored to look something like this:

            const string userName = "Mats";
            const string emailAddress = "";

            var tester = ResetPasswordTester
                .WithUser(userName, emailAddress);


            tester.Mailer.Verify(d => d.SendMail(emailAddress));

Attached to this post is a simple implementation using Moq, and the dummy ResetPassword test class. Replacing Moq with something else like NSubstitute, FakeItEasy is extremely simple.



Solving setTimeout-problem using QUnit and SinonJS

Recently had a problem testing setTimout-callbacks when using the QUnit javascript testing framework and also adding SinonJS to the mix for faking xmlHttp-requests. Could not get the callback to fire. After a long time trying different examples using QUnit and SinonJS I finally got my facepalm moment and solved it.

When adding the Sinon javascript and sinon-qunit script the QUnit script has a config section that enables useFakeTimers by default, so the clock wouldn’t tick/advance by default.

If you really want to use setTimeout the QUnit way (start/stop-functions), then your tests will have to wait until timeout elapses

A better way is to use sinon’s fake timers. a trivial example:

test("test with useFakeTimers", function () {

  setTimeout(function () {
    ok(true, "timeout sucessfully called");
  }, 150);


and if you have useFakeTimers = true in your sinon-qunit-javascript you can even remove this.sandbox.useFakeTimers()

note: as of february 2010 the source at github has changed to have useFakeTimers disabled by default.


Serialize .NET objects as camelCase JSON

ASP.NET MVC is amazing how easy it is to serialize from a .NET POCO to JSON and the other way around using the model binder. But one thing I really don’t like is how serializing .NET objects to JSON returns the properties PascalCase.

Net has PascalCase coding convention for properties and JavaScript uses camelCase.

The solution is to use Json.NET to serialize the objects (which will be included by default in Visual Studio 2012).

Continuing on the previous blog post you would then

Install Newtonsoft Json.NET using NuGet.

Modify the controller so instead of returning

return Json(new Dog { Name = "Rambo", Age = 5 }, JsonRequestBehavior.AllowGet);

you would create a JsonSerializerSettings, Serialize the object with JsonConvert and return the content with content type application/json

public ActionResult Load()
  var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
  var json = JsonConvert.SerializeObject(dog, Formatting.Indented, jsonSerializerSettings);

  return Content(json, "application/json");

which would give you

  "name": "Rambo",
  "age": 5

instead of

  "Name": "Rambo",
  "Age": 5

Of course you would have to update your bindings and ViewModel-data to use camel case instead of pascal case.

And when sending camelCase JSON to your controller the modelbinder automatically handles it and deserializes it correctly.

I have included a updated example solution from the previous blog post where I have created a JsonCamelCaseResult inherited from ActionResult.


return new JsonCamelCaseResult
                   Data = new Dog { Name = "Rambo", Age = 5 }, 
                   JsonRequestBehavior = JsonRequestBehavior.AllowGet
              }; (465.98 kb)

Automatic mapping with Knockout.js, the mapping plugin and ASP.NET MVC 3

Expected outcome

  • Having a C# Dog class with name and age-properties.
  • When the page loads, it automatically loads the dog using jQuery ajax (serialized as json) and creates a knockout viewmodel.
  • ViewModel should automatically add properties from the C# model.
  • The knockout ViewModel should be able to have extra computed methods for validating form for example.
  • The ViewModel should be able to save the dog using ajax.

Installing components

Install Knockout.Mapping using NuGet, this will automatically install Knockout.

Create Model

First, create the dog, a simple C# plain object with two properties: Name and Age

public class Dog
    public string Name { get; set; }
    public int Age { get; set; }

Create MVC Controller

Then create a empty DogController and add a empty Index method. The Load method just creates a simple instance of a dog and returns it as Json, and finally the Save method only accepts post data and just returns a formatted string in Json-format containing the updated Dog

public class DogController : Controller
    public virtual ActionResult Index()
        return View();

    public ActionResult Load()
        return Json(new Dog { Name = "Rambo", Age = 5 }, JsonRequestBehavior.AllowGet);

    public ActionResult Save(Dog dog)
        return Json(new { Status = string.Format("Success, saved {0} with age: {1}", dog.Name, dog.Age) });

Create View

Create empty Index View and add script-references

<script src="@Url.Content("~/Scripts/knockout.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-mapping-latest.js")" type="text/javascript"></script>

Then you add a form containing the knockout bindings bound to the observables on the ViewModel. Two input boxes data bound to Name and Age, the submit-action to “save”, a function on the JavsScript ViewModel, and finally data-bind the submit button so it’s enabled only if the model is valid.

<form method="POST" data-bind="submit: save">
    <div><input type="text" data-bind="value: Name" /></div>

    <div><input type="text" data-bind="value: Age" /></div>

    <div><input type="submit" value="Save" data-bind="enable: isValid()" /></div>

Create ViewModel

Create a class in JavaScript, taking JSON data to be mapped as parameter, and add isValid as a computed property and finally a save function that posts the JSON-data back to the DogController’s Save method.

var ViewModel = function (data) {
	var self = this;
	ko.mapping.fromJS(data, {}, self);

	self.isValid = ko.computed(function () {
		return > 0;
	}); = function () {
			url: "Knockout2/Save",
			type: "post",
			contentType: "application/json",
			data: ko.mapping.toJSON(self),
			success: function (response) {

Load initial data

Finally you add a JavaScript document ready handler that loads the initial data. Place it below the ViewModel.

$(function () {
    $.getJSON("Dog/Load", null, function (data) {
        ko.applyBindings(new ViewModel(data));


This is probably not the best way, and of course there are lots of stuff you should do. For example, move javascript references to bottom of page, validate the postback and more. But I tried to keep the example as simple as possible.

Download the project here: (456.44 kb)

Create Html.DropdownListFor without magic strings

Using magic strings are bad practice. Changes could lead to code compiling but containing lots of errors (appearing during runtime). And refactoring your code is a lot harder if you have to globally search and replace.

Using dropdown lists with ASP.NET MVC has a Html-helper that wants you to use magic strings. Having a Category class:

    public class Category
        public int CategoryId { get; set; }
        public string Name { get; set; }

And a viewmodel:

    public class DropdownViewModel
        public int CategoryId { get; set; }
        public Category[] Categories { get; set; }


You would then use the html-helper like this:

    public static class ExtensionMethods
        public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> enumerable, Func<TItem, TValue> value, Func<TItem, string> text, string defaultText = null, string defaultValue = null)
            var itms = enumerable.Select(f => new SelectListItem { Text = text(f), Value = value(f).ToString() }).ToList();
            if (defaultText != null)
                itms.Insert(0, new SelectListItem { Text = defaultText, Value = defaultValue ?? "0" });
            return itms;

Now it’s easy to just use lambdas and, this little extension method has a couple of overloads.

Html.DropDownListFor(m => m.CategoryId, 
    Model.Categories.ToSelectList(f => f.CategoryId, f => f.Name))

Usage is really easy, just use the extension method on the Array you wish to create a dropdown items from.

Now your code is refactor safe

First parameter: Selected item in model

Second parameter: Id/value-item (generic TValue, so you can use for example int’s without calling ToString()

Third parameter: Text to display for each item in dropdown

Fourth parameter(optional): Empty default-text (first item in dropdown), uses value “0″ if fifth parameter isn’t supplied

Fifth parameter(optional): Empty default-value

Category: C#

Creating and intitializing ArrayList in one line

There are multiple ways of creating a ArrayList and adding a couple of items to it. 

The usual way to do it:

List<String> normal = new ArrayList<String>();

Or you could use the double braces. The inner pair of braces creates a anonymous innner class

List<String> doubleBraces = new ArrayList<String>() {{

But I prefer to use a small static method that uses generics and varargs to accomplish the same thing.

public class Simple {

	public static <T> ArrayList<T> listOf(T... elements) {
		ArrayList<T> list = new ArrayList<T>();
		for (T element : elements) {
		return list;

And to use it you just write:

List<String> simple = Simple.listOf("one", "two", "three");