Serializing .NET dictionary

Standard

Recently I had to implement XML Serialization in one of my class, it was deriving from base class, which has a dictionary property and XML Serialization was failing due to that. And here is the code snippet which will help you to serialize a .Net dictionary. It is implemented using IXmlSerializable interface

Here is the Unit Tests (It was TDD implementation :))

[TestClass]
    public class SampleTests
    {
        [TestMethod]
        public void TestSampleCanBeSerialized()
        {
            var sample = new Sample();
            sample.Colors = new Dictionary<int, string>();
            sample.Colors.Add(1, "Red");
            sample.Colors.Add(2, "Blue");
            Serialize(sample);
        }

        [TestMethod]
        public void TestSampleIsProperlySerialized()
        {
            var sample = new Sample();
            sample.Colors = new Dictionary<int, string>();
            sample.Colors.Add(1, "Red");
            sample.Colors.Add(2, "Blue");
            var result = Serialize(sample);            
            Assert.IsNotNull(result);
            var newsample = DeSerialize(result);

            Assert.IsNotNull(newsample,"Sample not created");
            Assert.IsNotNull(newsample.Colors,"Couldn't create colors");

            Assert.AreEqual(2, newsample.Colors.Count);
        }

        private static string Serialize(Sample sample)
        {
            using (var stringWriter = new StringWriter())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Sample));
                xmlSerializer.Serialize(stringWriter, sample);
                return stringWriter.ToString();
            }
        }

        private static Sample DeSerialize(string text)
        {
            using (var stringReader = new StringReader(text))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Sample));
                return xmlSerializer.Deserialize(stringReader) as Sample;
            }
        }

    }
}

Here is the actual implementation.

public class Sample : IXmlSerializable
{
    public Dictionary<int, string> Colors { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        var xmlDocument = new XmlDocument();
        xmlDocument.Load(reader);
        var colors = xmlDocument.SelectNodes("//Color");
        Colors = new Dictionary<int, string>();
        foreach (XmlNode color in colors)
        {
            Colors.Add(int.Parse(color.Attributes["Key"].Value.ToString()), color.Attributes["Value"].Value.ToString());
        }
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement("Sample");
        writer.WriteStartElement("Colors");
        foreach (var color in Colors)
        {
            writer.WriteStartElement("Color");
            writer.WriteAttributeString("Key", color.Key.ToString());
            writer.WriteAttributeString("Value", color.Value);
            writer.WriteEndElement();
        }
        writer.WriteEndElement();
        writer.WriteEndElement();
    }
}

Happy Programming :)

Test-driven development in Javascript

Standard

Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.
Here is fundamental mantra of TDD:

  1. Write a test and make it fail.
  2. Make the test pass.
  3. Refactor.
  4. Repeat.

This technique also referred as “Red-Green-Refactor” because IDE’s and test runners use red color to indicate failed tests and green color to indicate the tests that passed.

For TDD in Javascript I am using a javascript library called QUnit. QUnit now runs completely standalone and doesn’t have any jQuery dependencies. While it’s still being used by the jQuery Project itself for testing jQuery, jQuery UI and jQuery Mobile code, QUnit can be used to test any generic JavaScript code. You require QUnit javascript and css file. You can download it and use it or you can use the JQuery CDN.

First you need to create the Test Runner, it can be an HTML file, which contains links to the QUnit Framework and your test cases. Here is the code for minimal test runner.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="scripts/qunit-1.14.0.js"></script>
    <script src="scripts/functions.js"></script>
    <script src="scripts/tests/tests.js"></script>
    <link href="styles/qunit-1.14.0.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div id="qunit"></div>
        <div id="qunit-fixture"></div>
    </form>
</body>
</html>

This DIV with Id “qunit” will display the results. And the DIV with id “qunit-fixture” will display any test case related information.

Now you need to start writing tests. For the demo purposes I am creating an Age calculator, which will take your Date of Birth as the argument and returns the number of years. Here is my calculator class.

function AgeCalculator() {

}

And here is my first unit test, which will verify the GetAge function exists or not.

test("Verify Calculate function exists", function () {
    var calc = new AgeCalculator();
    ok(typeof (calc.Calculate) === "function");
});

And open the test runner HTML. As we don’t have a function like that, it will fail.

QUnit - Test Failed

QUnit – Test Failed

Now you to write minimal code to pass the test.

function AgeCalculator() {

}
AgeCalculator.prototype.Calculate = function (date) {

}; 

Here is the calculate function which doesn’t not do anything, but helps to pass the first test. Now open the test runner again, and refresh the page.

QUnit - Test Passed

QUnit – Test Passed

Now you need to write a test which will verify the functionality, like the Calculate function should return a positive integer.

test("Verify Calculate function returns Age", function () {
    var calc = new AgeCalculator();
    ok(calc.Calculate(new Date(1981, 10, 20)) == 32);
});

As expected this test will also fail, because we don’t have anything implemented in the Calculate function. Now let’s write some code to pass this test as well.

AgeCalculator.prototype.Calculate = function (date) {
    var ageDifMs = Date.now() - date.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
};

Now the second test will pass.

QUnit - 2 Tests Passed

QUnit – 2 Tests Passed

Now we can do some refactoring the unit tests, if you look into the test code, we are are duplicating the initialization of AgeCalculator. Either you can create a method which will return the instance, and call the function in the initialization or you can create a QUnit module and can use the framework feature for initialization before running every tests.

Here is the implementation.

var calc;
module("Age Calcualtor Tests", {
    setup: function () {
        calc = new AgeCalculator();
    },
    teardown: function () {
        // clean up after each test
    }
});
test("Verify Add function exists", function () {
    ok(typeof (calc.Calculate) === "function");
});

test("Verify Calculate function returns Age", function () {
    ok(calc.Calculate(new Date(1981, 10, 20)) == 32);
});

And here is the screenshot for the same.

QUnit Module

QUnit Module

If you are using Visual Studio, there is a nice test adapter available for Javascript unit testing. It is called “Chutzpah – A JavaScript Test Runner”. You can download it from http://chutzpah.codeplex.com/, which helps to run javascript test cases from Visual Studio itself. It is also supports Continuous integration too.

Visual Studion 2012 - Test Explorer

Visual Studion 2012 – Test Explorer

ReSharper also supports Javascript unit testing.

Here is links which may help you.

Happy Programming :)

Unit testing ASP.NET Web API Controller

Standard

This post is about unit testing Web API controller. As we are using Entity Framework and some Web API related classes, we need to implement dependency injection to unit test Web API controllers.

To manage Entity Framework dependency, I am using a simple Repository pattern. Here is my repository interface.

public interface IRepository
{
    IEnumerable<Employee> ReadAll();
    Employee ReadById(int id);
    int Create(Employee employee);
    int Update(int id, Employee employee);
    int Delete(int id);
}

As this post is more focusing on unit testing, I am not including the implementation of the IRepository interface, it is same as we used in the controller. And I am modified the controller like this, one more constructor added, which accepts IRepository as one parameter.

private readonly IRepository _employeeRepository;
public EmployeeController()
    : this(new EmployeeRepository())
{
//Empty constructor.
}
//For Testability
public EmployeeController(IRepository repository)
{
    _employeeRepository = repository;
}

And the Get methods in the controller is modified like this.

public HttpResponseMessage Get()
{
    return Request.CreateResponse<IEnumerable<Employee>>
                    (HttpStatusCode.OK, _employeeRepository.ReadAll());
}

public HttpResponseMessage Get(int id)
{
    var selectedEmployee = _employeeRepository.ReadById(id);
    if (null != selectedEmployee)
    {
        return Request.CreateResponse<Employee>
            (HttpStatusCode.OK, selectedEmployee);
    }
    else
    {
        return Request.CreateErrorResponse
            (HttpStatusCode.NotFound, "Employee not found");
    }
}

Instead of using Entity Framework directly, interacting to DB via Repository. You can write the unit test like this to verify the Get method.

//ARRANGE
var expected = new List<Employee>(1) { 
    new Employee() { Id = 1, Email = "email", Name = "name", Phone = "123" }
};
Mock<IRepository> mockRepository = new Mock<IRepository>();
mockRepository.Setup(x => x.ReadAll()).Returns(() => expected);
var controller = new EmployeeController(mockRepository.Object);
controller.Request = new HttpRequestMessage()
{
    Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
};
//ACT
var response = controller.Get();

//ASSERT
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var actual = response.Content.ReadAsAsync<List<Employee>>().Result;
Assert.AreEqual(expected.Count, actual.Count);

For mocking purposes I am using Moq library. As we are using the Request property to create the HttpResponseMessage, you need to set a default value to the request property, otherwise you will get some null reference exception from the unit test.

Similar to Request property, in the post method we are using the Url property from APIController class, which is an instance of the UrlHelper class. Unlike the Request property, Url property is quite complex to create, so I am using a wrapper class, which will wraps the Url.Link() method. And I created an interface like this.

public interface IUrlHelper
{
    string GetLink(string routeName, object routeValues);
    UrlHelper Url { get; set; }
}

And the implementation is like this.

public class CustomUrlHelper : IUrlHelper
{
    public UrlHelper Url { get; set; }

    public string GetLink(string routeName, object routeValues)
    {
        return Url.Link(routeName, routeValues);
    }
}

To use the IUrlHelper interface, I modified the controller class again like this.

private readonly IRepository _employeeRepository;
private readonly IUrlHelper _urlHelper;

public EmployeeController()
    : this(new EmployeeRepository(), new CustomUrlHelper())
{
    _urlHelper.Url = Url; //In controller empty constructor, you need to set this property.
}
//For Testability
public EmployeeController(IRepository repository, IUrlHelper urlHelper)
{
    _employeeRepository = repository;
    _urlHelper = urlHelper;
}

Both Post and Put method modified to use _urlHelper, instead of the Url property.

public HttpResponseMessage Post(Employee employee)
{
    _employeeRepository.Create(employee);
    var response = Request.CreateResponse<Employee>
        (HttpStatusCode.Created, employee);
    response.Headers.Location = 
        new Uri(_urlHelper.GetLink("DefaultApi", new { id = employee.Id }));
    return response;
}

Here is the test method for verifying the Post method in the controller.

//ARRANGE
var isCreatedInvokedInRepository = false;
var employee = new Employee()
{
    Id = 1,
    Email = "email",
    Name = "name",
    Phone = "phone"
};

var mockRepository = new Mock<IRepository>();
var mockUrlHelper = new Mock<IUrlHelper>();
mockUrlHelper.Setup(x => x.GetLink(It.IsAny<string>(), It.IsAny<object>()))
    .Returns("http://localhost/webapi/employee/");
mockRepository.Setup(x => x.Create(It.IsAny<Employee>())).
    Callback(() => isCreatedInvokedInRepository = true);
var controller = new EmployeeController(
    mockRepository.Object, mockUrlHelper.Object);
controller.Request = new HttpRequestMessage()
{
    Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
};

//ACT
var response = controller.Post(employee);

//ASSERT
Assert.IsTrue(isCreatedInvokedInRepository,
    "Create method in Repository not invoked");
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
Assert.IsNotNull(response.Headers.Location);

You can write similar tests for all the other methods.

Happy Unit testing.

Unit Testing Windows Phone Applications

Standard

Recently Microsoft released Update 2 for Visual Studio 2012. If you installed the Update 2, you will get a new project template, under Windows Phone, Windows Phone Unit Test App.

Windows Phone Unit Test App - Project Template

This will help you to create unit test project for Windows Phone 8 applications. Once you create the project, necessary references will be added to the project by Visual Studio.

Windows Phone Unit Test App - Project References

If you are familiar with MS Test, you don’t need to learn any new framework for testing phone apps.
The Windows Phone test framework is designed as an adapter on top of the extensible Visual Studio 2012 unit testing platform. So you can run the tests from VS 2012 IDE itself.

Running Windows Phone Unit Tests from VS 2012 IDE

You can run the tests from console also, using vstest.console.exe. You can also choose to export the results to Visual Studio Test Results File using /Logger:trx command line switch. This unit testing feature is supported in Express Edition also.

Happy Programming