Async unit test

With the .NET framework 4.5 making stuff asynchronous has become very easy with async-await. I’ve looked into unittesting this new way of programming and found that Microsoft thought about this too.

During my exercise I had to replace my trusted RhinoMocks by NSubstitute when the tests are run in parallel. Seems that RhinoMocks is not thread safe. More about that in the references.

Object under test

For my demos I’ve created a business object called Garage that uses a data repository to save Cars.

public interface IRepository {
    Task<int> CreateCar(Car carToCreate);
}
public class Garage {
    private IRepository Repository { get; set; }
    public Garage(IRepository repository) {
        Repository = repository;
    }
    public async Task<int> AddCar(Car carToAdd) {
        // add some logic here to validate the car
        var newId = await Repository.CreateCar(carToAdd);
        return newId;
    }
}
public class Car { }

Three tier architecture.

Unit test

There are a few ways to mock the repository call in the AddCar method. I’ll try to show the different approaches in the code samples below.

[TestMethod]
public void Garage_addCar_returns_1_run() {
    var validCar = CreateValidCar();
    var fakeRepository = Substitute.For<IRepository>();
    fakeRepository
        .CreateCar(validCar)
        .Returns(Task.Run<int>(() => 1));
    var garage = CreateGarage(fakeRepository);

    var result = default(int);
    var task = garage.AddCar(validCar);
    task.Wait();
    result = task.Result;

    Assert.AreEqual(1, result);
}

This first code shows that the repository creates a task and runs it to return the result (1). Then after the call to the garage.AddCar we’ll have to wait for the task to complete and collect the result.

When CreateCar is called a Task is run. There is some overhead setting this up by the framework. For testing purposes use the Task.FromResult.

[TestMethod]
public void Garage_addCar_returns_2_fromresult() {
    var validCar = CreateValidCar();
    var fakeRepository = Substitute.For<IRepository>();
    fakeRepository
        .CreateCar(validCar)
        .Returns(Task.FromResult<int>(2));
    var garage = CreateGarage(fakeRepository);

    var result = default(int);
    var task = garage.AddCar(validCar);
    task.Wait();
    result = task.Result;

    Assert.AreEqual(2, result);
}

With Task.FromResult no actual thread is spawn, but the result is returned immediate as if it is from a task. We still have to wait for the AddCar to finish.

Async unit test

A unittest is a method. That method can be async as well. See the code below that correspondents with the first unittest that creates and runs an actual task.

[TestMethod]
public async Task Garage_addCar_returns_11_run() {
    var validCar = CreateValidCar();
    var fakeRepository = Substitute.For<IRepository>();
    fakeRepository
        .CreateCar(validCar)
        .Returns(Task.Run<int>(() => 11));
    var garage = CreateGarage(fakeRepository);

    var result = default(int);
    result = await garage.AddCar(validCar);

    Assert.AreEqual(11, result);
}

The method must return a Task for the MSTest framework to wait on and is marked async so the garaga.AddCar can be await.

We can improve the unittest by using the Task.FromResult.

[TestMethod]
public async Task Garage_addCar_returns_12_fromresult() {
    var validCar = CreateValidCar();
    var fakeRepository = Substitute.For<IRepository>();
    fakeRepository
        .CreateCar(validCar)
        .Returns(Task.FromResult<int>(12));
    var garage = CreateGarage(fakeRepository);

    var result = default(int);
    result = await garage.AddCar(validCar);

    Assert.AreEqual(12, result);
}

There is less clutter for handling the async method. Unittesting is all about Readable, Trustworthy, Fast and Maintainable 🙂

References

Posted in Development | Tagged , , , | Leave a comment

Remote debugger extension

The Server Explorer in Visual Studio holds a hidden gem: the debugger extension for Azure. This integration is documented on MSDN but I just recently found it.

enable_debugging

Integration makes it easier to debug in azure. Just enable debugging and attach to the process.

References

Debugging Azure virtual machines by installing the remote debugger extension.
Article about this in SDN Magazine written by me (dutch)

Posted in Tooling | Tagged , , | Leave a comment

Week 8 roundup

Last week recap and links:

Image courtesy of kanate / FreeDigitalPhotos.net

Image courtesy of kanate / FreeDigitalPhotos.net

What are your best reads this week? Leave them in the comments below.

Posted in Uncategorized | Tagged , , , | Leave a comment

Know your user

When we create a (web) application the GUI must be responsive on every platform. All kinds of frameworks and scripts help us to achieve the best experience on every device. But what about operations? Do they get the best experience?

Management of the application is programmed on forms with import buttons and security checks. No automation, no reuse of modules, no real bulk operations and a Change Request when the import format changes. We end up with a tool that costs to much and no user satisfaction.

powershellThe main tool in operations is powershell. We should embrace this in our DEVOPS thinking. You can offer more functionality in the module, move the import/file format out-of-scope and use the automation yourself for continuous deployment.

Create a powershell module for the management of your application and show you know your user.

Posted in Uncategorized | Tagged | Leave a comment

Bind WPF control to Window property

I’ve decided to write this small post on how to bind a WPF control to a property of the Window code behind. Every time I forget one of the steps and end up searching for this:

  1. Create a dependency property, you can use the propdp code snippet
  2. Name the window, by setting the Name property in the <Window > tag
  3. Bind using ElementName and Path, set the Path to the dependency property (1) and ElementName to the window name (2)

Example with a label bind to a string property of the MainWindow.

// 1. create a dependency property with the propdp code snippet
public string MyRandomText
{
    get { return (string)GetValue(MyRandomTextProperty); }
    set { SetValue(MyRandomTextProperty, value); }
}
public static readonly DependencyProperty MyRandomTextProperty =
    DependencyProperty.Register("MyRandomText", typeof(string), 
    typeof(MainWindow), new PropertyMetadata(Guid.NewGuid().ToString())
);
<Window x:Class="BindControlToWindowProperty.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" 
        Name="MyWindow"> <!-- 2. Name the Window -->
    <Grid>
        <!-- 3. Bind using ElementName and Path -->
        <Label Content="{Binding ElementName=MyWindow,Path=MyRandomText}"/>
    </Grid>
</Window>
Posted in Development | Tagged , | Leave a comment