Stubs with “ActiveRecord for Azure”
In a previous post I showed how to do basic CRUD operations with my sample ActiveRecord implementation for Windows Azure Tables. The attentive reader probably noticed my use of ASP.NET MVC and static methods on the entity for operations like Find and Delete. Most of the times statics like this are bad when it comes to testability, because they're hard to stub out. But just like ASP.NET MVC - "ActiveRecord for Azure" was designed with testing in mind.
If we have a look on the test for the Create action, it first setups the Task entity for testing by calling its static Setup(int) method. By calling Setup it will use a local, in memory, repository and populate it with the given number of entities.
[Fact]
public void it_creates_new_task() {
Task.Setup(0); //setup for test but don't create entities
var controller = new TasksController();
controller.Create(new Task());
Assert.Equal(1, Task.All().Count());
}
The Setup method also allows you to specify how the pre-populated entities will be initialized with data. In the example below the Task repository will be populated with one Task with a RowKey of "1" and a PartitionKey of "AR4A".
[Fact]
public void it_should_display_requested_task() {
Task.Setup(1)
.With(x => x.RowKey).Returns("1")
.With(x => x.PartitionKey).Returns("AR4A"); //for now..
var controller = new TasksController();
var result = controller.Edit("1") as ViewResult;
Assert.Equal("1", ((Task)result.ViewData.Model).RowKey);
}
So the stubs support in "ActiveRecord for Azure" basically shows how to substitute the "cloud aware" DataServiceContext with an in-memory context, allowing you to unit test your applications without accessing Windows Azure Table Storage.
The above examples are available in the download below.
The complete “ActiveRecord for Azure” sample source is available here.