Tag Archives: unit test

BDD Style Test Phrasing… What’s Your Poison?

I’ve had this question come up a few times recently, and I wanted to get everybody’s take on it…  when you write BDD style tests, what practice do you prefer?

…I’ll have a follow up to this poll in a few days and explain some of my own reasoning to the whole situation.

WebStorm JavaScripting & Noding Workflow Webinar Recording

Today the JetBrains team wrapping up final processing for my webinar from last week. You can check out the webinar via their JetBrains Youtube Channel:

JavaScriptFor even more information be sure to check out the questions and answers on the JetBrain WebStorm IDE blog entry. Some of the questions include:

  • Q: How to enable Node.js support in PhpStorm (PyCharm, IntelliJ IDEA, RubyMine)?
  • Q:How to enable autocompletion for Express, Mocha and other libraries?
  • Q: Is it possible to debug a Node.js application that runs remotely? Is it possible to debug when your node and the rest of the dependencies (database, etc.) are running in a VM environment like Vagrant?
  • Q: Does the debugger support cluster mode?

…and others all here.

HTML, CSS, JavaScript and Metro App Building on Windows 8 Part 2

In the first part of this seriesI kicked everything off by starting a Windows 8 JavaScript Project and added QUnit-Metro via Nuget. Now that we have a small executable application, I’ll get some things added and cover what exactly it is we’re doing in each part. Open the project up that we created in the previous blog entry of the series. Once open find and open the default.html, default.js and default_tests.js files to work with. In the default.js file you’ll find the following code in the default.js.

(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
            } else {
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
    };

    app.start();
})();

A Bit of Context – default.js

At the beginning you’ll find that all the code is enclosed in a self-executing anonymous function. This gives us the ability to avoid naming conflicts or accidentally modifying variables in other spaces. Kind of the “namespaces” of C# or other organizational code features from other languages (I said kind of, there are other ways to do this too, this is just one). The other cool thing about this is it keeps identifiers out of the global namespace which also helps performance (it’ll also get you called all sorts of stuff if you create global variables in JavaScript! I’m nice, I won’t do it, but be prepared to be appropriately punished for such dissension as global variable creation! I warned ya.).

This next part (reminds me of why I find JavaScript scary in addition to awesome) has a variable that turns “strict mode” on. What this does, just like those of you may know from the Visual Basic days, is turn on a strict mode of additional error checking for code. It helps prevent you from doing all sorts of dumb things, like trying to assign a value to a read-only variable. For more on “strict mode” check out Microsoft’s Strict Mode Page.

The remaining bits of code in the default.js are the handlers for the application activated and checkpoint events. These events are fairly self explanatory, suffice it to say they happen when the application launches and checkpoint fires when a particular checking event happens against the Process Lifetime Management. The Process Lifetime Management handles all of the application suspend, resume and background events.

TDD & BDD For The Win!

Ok, so this isn’t the best example of either really, but to get started we want to wire up an event to a button. But first we want to test if the event is wired up. How does someone tests if an event is wired up in JavaScript? Like this.

test("Where the text box is populated ", function () {
    var result = document.getElementById("messageOutput").innerText;
    ok(result == "", "should have empty inner text.");
});

Adding a Button & Some Button Functionality

Ok, done with the context. Let’s add a button and make some magic happen. Bring focus to the default.html page and add a button, a text box and the respective components.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Readingz</title>
    <!-- These files are included when the project is generated, I don't really know where they are... -->
    <link href="//Microsoft.WinJS.1.0.RC/css/ui-light.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
    <!-- Turned on the testing. -->
    <script src="/js/qunitmetro.js"></script>
    <script src="/js/default_tests.js"></script>
    <!-- Default Metro files. -->
    <script src="/js/default.js"></script>
    <link href="/css/default.css" rel="stylesheet" />
</head>
<body>
    <p>Click the button to run the tests for the default.html and default.js code.</p>
    <input id="peripheralParameters" type="text" />
    <button id="runTests">Run Tests</button>
    <p id="messageOutput"></p>
</body>
</html>

NOTE: I made more than a few changes from the default.html included in the previous part of this series. One hard to notice change is that I switched the style sheet from the dark Metro theme to the light Metro theme.

With those additions add a function to the default.js file as shown below and then add the event handler.

(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {

            } else {

            }
            args.setPromise(WinJS.UI.processAll());

            var runTests = document.getElementById("runTests");
            runTests.addEventListener("click", buttonClickHandler, false);
        }
    };

    app.oncheckpoint = function (args) {};

    function buttonClickHandler () {
        document.getElementById("messageOutput").innerText =
           "Parameters Passed: " +
           document.getElementById("peripheralParameters").value +
           "!";
    }

    app.start();
})();

I now have one button now working, actually doing something, with a unit tests to verify that the button exists and the event is wired up. Some progress is being made!

If I run the application I get passing tests. That’s it for now. In the next entry we’ll dive deeper into testing and into functionality.

Until next time, happy scripting with the JavaScript on Windows 8.

OS-X Cocoa Quickie #1 => Make Sure to Have Unit Tests

When starting an Xcode Cocoa Project you should have a testing project that you include. It’s a simple check box on the project creation dialogs.

Keep This Checked! Write Tests!

Keep This Checked! Write Tests!

If for some reason you inherit a project that doesn’t have unit tests, tests, or anything of the sort and need to add a testing project follow these steps. With the project open add a new target as shown below.

Add a New Target to the Project

Add a New Target to the Project

Add a Cocoa Unit Testing Bundle.

Cocoa Touch Unit Testing Bundle

Cocoa Touch Unit Testing Bundle (Click for full window and full size image)

Set the appropriate parameters for your project. Be sure to select the project from the drop down.

Set the product name and be sure to select the correct Project from the drop down. (Click for full window and full size image)

Set the product name and be sure to select the correct Project from the drop down. (Click for full window and full size image)

Once finished adding the testing target, edit the schema. The project will have an additional schema. I personally like to keep them rolled together, so delete the “*Tests” schema and just make sure that the Tests section has the right target listed.

Schema Settings

Schema Settings

If it isn’t listed, as shown in the above dialog, click the + to add the tests project. Select it in the target dialog as shown below.

Adding the test target for the schema

Adding the test target for the schema

Once all that is done then the tests can be executed from the Product -> Test menu option or the shortcut key combo of ⌘U. With the default code that is added to the target project, you’ll end up with one failing test.

Test FAIL!

Test FAIL!

Now write tests!

A TimePiece of C# and JavaScript

I put together a little project on Github, partially because I’ve been making headway learning the intricacies of JavaScript, and partly because I wanted something that would parse a string that represents a time value. So here’s the TDD I went through. In the process I pulled in QUnit and used that as my testing framework for the JavaScript example. I’d love input on either of these, so feel free to gimme some heat, tell me what I’ve done wrong, and especially how I ought to be doing this.  🙂

The first thing I did was put together the C# Library. I started two projects, one for the tests and one for the actual library.  In the tests project I added a class file and removed the default using statements and replaced them with the following by way of Nuget:

using NUnit.Framework;
using Shouldly;

After adding these references I jumped right into setting up the test fixture. Since I know I want to have something to parse the hour for military time also I’ve setup two test variables.

[TestFixture]
public class with_static_parsing_of_time
{
    protected string sampleTimeOne = "10:12am";
    protected string sampleTimeTwo = "2:30pm";

The first test I then dived into was to test the hour.

[Test]
public void should_return_a_time_piece_with_correct_hour()
{
    var timePiece = TimePiece.Parse(sampleTimeOne);
    timePiece.Hour.ShouldBe(10);
}

I then fleshed out the object and implemented enough to get this test to pass.

namespace TimeSlicer
{
    public class TimePiece
    {
        public TimePiece(string time)
        {
            ParseTime(time);
        }

        private void ParseTime(string time)
        {
            SetHour(time);
        }

        private void SetHour(string time)
        {
            Hour = Convert.ToInt32(time.Split(Convert.ToChar(":"))[0]);
        }

        public int Hour { get; set; }

I then continued back and forth writing tests and implemented each. For the complete code check out the Github Repository. This example is really simple. I’d love any thoughts on adding to it or what you might think is a better way to test the object.

For the JavaScript I downloaded QUnit. Again I stepped into the testing, which is a whole different ballgame than in C#.

<link rel="stylesheet" href="qunit/qunit.css" type="text/css" media="screen"/>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript" src="qunit/qunit.js"></script>
<script type="text/javascript" src="TimeSlicer/TimePiece.js"></script>
<script type="text/javascript">

var timeValueOne = "1:30am";
var timeValueTwo = "8:15pm";

$(document).ready(function() {

module("Parse hour from value.");

test("Should parse hour from value.", function() {
    TimePiece(timeValueOne);
    equal(TimePiece.Hour(), 1, "The appropriate hour value is returned for AM meridian value.");
});

For the full test file with other JavaScript libraries and CSS check out the code file on github.

…and directly into implementation. With the caveat that I’m extremely unfamiliar with actual psuedo/pretend/faux object creation in JavaScript. In this realm I’m still reading up on best ways to do this.

TimePiece = function(time) {
    TimePiece.Hour = function () {
        return time.toString().split(":")[0];
    }
    return time;
};

I went on from here writing tests and implementing as I did with the C#. The JavaScript was interesting. I’ve also noticed that I get a lot of strings back versus the number values that I’d actually want, thus the addition of the “parseInt” in the final version.

Check out the overall project on Github at: https://github.com/Adron/Time-Slice

Windows Azure SDK Unit Testing Dilemma — F5DD Plz K Thx Bye

I’m a huge advocate for high quality code. I will admit I don’t always get to write, or am always able to write high quality code. But day in and out I make my best effort at figuring out the best way to write solid, high quality, easy to maintain, easy to read code.

Over the last year or so I’ve been working with Windows Azure (Amazon Web Services and other Cloud/Utility Platforms & Infrastructure also). One of the largest gaps that I’ve experienced when working with Windows Azure is the gross disregard for unit testing and especially unit testing in a Test Driven Development style way. The design of the SDK doesn’t make unit testing a high priority, and instead focuses mostly on what one might call F5 & Run Development.

I’ll be the first to stand up and point out why F5 Driven Development (for more on this, check out Jeff Schumacher‘s Blog Entry) is the slowest & distracting ways to build high quality code. I’d also be one to admit that F5 Development encourages poor design and development. A developer has to juggle far too many things to waste time hitting F5 every few seconds to assure that the build is running and code changes, additions, or deletions have been made correctly. If a developer disregards running the application when forced to do F5 Development the tendancy is to produce a lot of code, most likely not refactored or tested, during each run of the application. The list of reasons to not develop this way can get long pretty quick. A developer needs to be able to write a test, implement the code, and run the test without a framework launching the development fabric, or worse being forced to not write a test and running code that launches a whole development fabric framework.

Now don’t get me wrong, the development fabric is freaking AWESOME!! It is one of the things that really sets Windows Azure apart from other platforms and infrastructure models that one can develop to. But the level of work and effort makes effectively, cleanly, and intelligently unit testing code against Windows Azure with the development fabric almost impossible.

But with that context, I’m on a search to find some effective ways, with the current SDK limitations and frustrations, to write unit tests and encourage test driven design (TDD) or behaviour driven design (BDD) against Windows Azure, preferably using the SDK.

So far I’ve found the following methods of doing TDD against Windows Azure.

  • Don’t use the SDK. The easiest way to go TDD or BDD against Windows Azure and not being tightly bound to the SDK & Development Fabric is to ignore the SDK altogether and use regular service calls against the Windows Azure service end points. The problem with this however, is that it basically requires one rewrite all the things that the SDK wraps (albeit with better design principles). This is very time consuming but truly gives one absolute control over what they’re writing and also releases one from the issues/nuances that the Windows Azure SDK (1.3 comes to mind) has had.
  • Abstract, abstract, and abstract with a lock of stubbing, mocking, more stubbing, and some more abstractions underneath all of that to make sure the development fabric doesn’t kick off every time the tests are run.  I don’t want to abstract something just to fake, stub, or mock it.  The level of indirection needed gets a bit absurd because of the design issues with the SDK.  The big problem with this design process to move forward with TDD and BDD is that it requires the SDK to basically be rewritten as a whole virtual stubbed, faked, and mocked layer. Reminds me of many of the reasons the Entity Framework is so difficult to work with for testing (has the EF been cleaned up, opened up, and those nasty sealed classes removed yet??)

Now I’ll admit, sometimes I miss the obvious things and maybe there is a magic “build tests real easy right here” button for Windows Azure, but I haven’t found it.  I’d love to hear what else people are doing to enable good design principles around Windows Azure’s SDK. Any thoughts, ideas, or things I ought to try would be absolutely great – I’d love to read them. Please do comment!

Excel Helper Utilities Library Part Two

In the last entry I covered a range of utility class methods including appropriate unit tests.  Today I want to cover the first steps into the twisted world of Excel Development with C#.  Note, there are many things I probably will not mention that are pivotal to this code working.  Namely the order in which Excel objects & framework interfaces and components are instantiated are of massive importance within managed code.  So if you are following along, first do the exact example here and then step on to changes.  That way you will have working code before arbitrarily having non-working code.

As always, tests are first.  In this entry I will actually step from test, to code, then green light the test for each part versus writing all the tests and then working through the methods.  That way I can cover each method and the purpose of the method.

Before even jumping straight into tests we will need to add two specific assemblies that are needed to test Excel appropriately;  Microsoft.Office.Interop.Excel and Microsoft.Office.Tools.Excel.v9.0.  (Click the images to see larger images)

Now to get started with Excel unit tests, we really do need to use the Excel Assemblies we’ve added because mocking just doesn’t cut it.  Because of the legacy code & other such droves of complexities, it is extremely hard to really mock accurately.  One really needs to know when the actual application is behaving appropriately under load & use from software written to use it.  With that said, here’s my first few tests & setup code.

I start out by creating the test class and creating a public property to act for all tests as the actual Excel Application under test.

[TestFixture]
public class ExcelHelperTests
{
    public Application ExcelApplication { get; set; }

Next I create two tests for setup and teardown of the Excel Application object.  In addition to the basic Excel Application object, one thing I have learned about Excel from experience, is that one needs to go ahead and immediately add a workbook.  If there is no workbook, Excel can throw all sorts of odd errors that provide very little insight into what is going on.  So just remove that possibility by adding that default workbook.

[TestFixtureSetUp]
public void CreateExcelAppAppropriately()
{
    ExcelApplication = new Application();
    ExcelApplication.Workbooks.Add(Type.Missing);
    ExcelApplication.Visible = true;
}
[TestFixtureTearDown]
public void QuitExcelAppAppropriately()
{
    foreach (Workbook workbook in ExcelApplication.Workbooks)
    {
        workbook.Close(false, false, Type.Missing);
    }
    ExcelApplication.Quit();
}

Now that this is setup I can really test how the class will react and behave under test with Excel.  Just to make sure, I verify that the appropriate Excel Application object is created and has a single workbook that was added in the fixture setup.

[Test]
public void InitializeDefaultWorkbook()
{
    Assert.GreaterOrEqual(1, ExcelApplication.Workbooks.Count);
}

Next on the list is finally getting to the real nitty gritty of the Excel Helper class I’m creating.  My first test to begin this class is as follows.

[Test]
public void ExcelHelperInstantiation()
{
    var excelHelper = new ExcelHelper(ExcelApplication);
    Assert.IsNotNull(excelHelper);
    Assert.IsNotNull(excelHelper.ExcelApplication);
}

With these tests throwing errors I’m now ready to add my initial class skeleton.

/// <summary>
/// This class provides helper utility methods for Excel 2007 that cover common
/// needs such as creating a new worksheet, or getting an insantiated instance
/// of an existing worksheet.
/// </summary>
public class ExcelHelper
{
    /// <summary>
    /// This class has a single constructor used to 
    /// setup the needed Microsoft.Office.Interop.Excel.Application
    /// object for use.
    /// </summary>
    /// <param name="excelApplication">Pass the active Excel Application
    /// object.</param>
    public ExcelHelper(Application excelApplication)
    {
        ExcelApplication = excelApplication;
    }
    /// <summary>
    /// This property is set to the active application the class
    /// executes methods against.
    /// </summary>
    public Application ExcelApplication { get; set; }
}

Run the test now and you should get a green light.  Moving along I added a test for the first method I want, a way to retrieve a Worksheet that already exists in Excel.  First my test looks something like this.

[Test]
public void GetWorksheet()
{
    var newWorksheet = ExcelApplication.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing,
                                                             Type.Missing) as Worksheet;
    const string newWorksheetName = "UniqueName";
    newWorksheet.Name = newWorksheetName;
    Worksheet foundNewWorksheet = new ExcelHelper(ExcelApplication).GetWorksheet(newWorksheetName);
    Assert.IsNotNull(foundNewWorksheet);
    Assert.AreEqual(foundNewWorksheet.Name, newWorksheet.Name);
}

I get a red light and then implement the code to return a Worksheet Object based on the passed in worksheet name.  It fails, since the method isn’t created, so I create the method.

/// <summary>
/// This method retrieves a specific worksheet by name.
/// </summary>
/// <param name="worksheetName">Pass the name of the
/// worksheet to retrieve.</param>
/// <returns>The Worksheet Object of the requested
/// worksheet, or if not found null.</returns>
public Worksheet GetWorksheet(string worksheetName)
{
    Worksheet foundSheet = null;
    foreach (Worksheet sheet in ExcelApplication.Worksheets)
    {
        if (sheet.Name == worksheetName)
            foundSheet = sheet;
    }
    return foundSheet;
}

Next test is for creating a new Worksheet, and adding it to the Excel Workbook.

[Test]
public void NewWorksheet()
{
    const string newWorksheetName = "UniqueName";
    new ExcelHelper(ExcelApplication).NewWorksheet(newWorksheetName);
    bool foundWorksheet = false;
    foreach (Worksheet worksheet in ExcelApplication.Worksheets)
    {
        if(worksheet.Name == newWorksheetName)
            foundWorksheet = true;
    }
    Assert.IsTrue(foundWorksheet);
}

Red lighted, so I add the method.

/// <summary>
/// This method creates a new worksheet with the name
/// specified.
/// </summary>
/// <param name="name">Pass the name you want the new
/// worksheet to have.</param>
/// <returns>Returns the new Worksheet object.</returns>
public Worksheet NewWorksheet(string name)
{
    var returnToThisWorksheet = ExcelApplication.ActiveSheet as _Worksheet;
    var returnSheet = ExcelApplication.Worksheets.Add(
                          Type.Missing,
                          Type.Missing,
                          Type.Missing,
                          Type.Missing) as Worksheet;
    returnSheet.Name = name;
    if (returnToThisWorksheet != null) returnToThisWorksheet.Activate();
    return returnSheet;
}

Now that I’ve simplified the methods to create and retrieve a worksheet from Excel, I want to add some functionality around determining if a Worksheet already exists within a workbook.  This is usually a common need within Excel and I find many examples are simply a foreach loop stepping through each Worksheet until it found or did not find the Worksheet it is looking for.  This is a perfect example of something that would be better as a method.

First the test, which I’ll make a static method in case one wants to call this method without instantiating?

[Test]
public void IsExistingWorksheetName()
{
    var newWorksheet = ExcelApplication.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing,
                                                                         Type.Missing) as Worksheet;
    const string newWorksheetName = "UniqueName";
    newWorksheet.Name = newWorksheetName;
    ExcelHelper.IsExistingWorksheetName(newWorksheetName, ExcelApplication.Worksheets);
}

and a test for a static method?

[Test]
public void IsExistingWorksheetNameInstantiatedMethod()
{
    var newWorksheet = ExcelApplication.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing,
                                                              Type.Missing) as Worksheet;
    const string newWorksheetName = "UniqueName";
    newWorksheet.Name = newWorksheetName;
    ExcelHelper helper = new ExcelHelper(ExcelApplication);
    Assert.IsTrue(helper.IsExistingWorksheetName(newWorksheetName));
    foreach (Worksheet sheet in ExcelApplication.Worksheets)
    {
        if (sheet.Name == newWorksheetName)
            sheet.Delete();
    }
    Assert.IsFalse(helper.IsExistingWorksheetName(newWorksheetName));
}

As I finished this test and got a red light I realized, I needed to assure the other tests cleaned up after themselves like this one does with the deletion of the Worksheet.  I then went back and add the snippet

foreach (Worksheet sheet in ExcelApplication.Worksheets)
{
    if (sheet.Name == newWorksheetName)
        sheet.Delete();
}

to each of the tests that needed it.  After the tests where appropriately refactored I ran the tests to assure they still where all green lights except for the one I just created.  I then jumped back into my ExcelHelper Class and created the methods I just wrote tests for.

/// <summary>
/// This method checks for existing names to prevent identical name collisions within the
/// worksheet collection.
/// </summary>
/// <param name="worksheetName">Pass in the worksheet name to check for.</param>
/// <param name="existingWorksheets">Pass in the Excel worksheets collection to search in.</param>
/// <returns>Return true if existing worksheet name is found, false if no existing worksheet names.</returns>
public static bool IsExistingWorksheetName(string worksheetName, Sheets existingWorksheets)
{
    foreach (_Worksheet worksheet in existingWorksheets)
    {
        string existingWorksheet = worksheet.Name;
        if (worksheetName == existingWorksheet)
            return true;
    }
    return false;
}
/// <summary>
/// This method checks for existing names to prevent identical name collisions within the
/// worksheet collection.
/// </summary>
/// <param name="worksheetName">Pass in the worksheet name to check for.</param>
/// <returns>Return true if existing worksheet name is found, false if no existing worksheet names.</returns>
public bool IsExistingWorksheetName(string worksheetName)
{
    return IsExistingWorksheetName(worksheetName, ExcelApplication.Worksheets);
}

For this entry we’ve covered appropriate tests and methods for getting an Excel Worksheet, creating a new Excel Worksheet, and finding out if a Excel Worksheet Name is already taken.  In my next entry on this topic I’ll keep adding more Excel Helper Methods that will help make Excel Addin Development easier.

kick it on DotNetKicks.com