Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Sunday, 18 November 2012

Unit testing Rx methods Timeout & Retry with moq

Posted on 07:52 by Unknown
Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran into an issue trying to mock out the Bar service so that it would cause the retry & timeout schedules to fire.

Bar is defined as follows, the implementation is irrelevant as it being mocked for the tests:

   1:  public interface IBarService
   2:  {
   3:      IObservable<Unit> Generate();
   4:  }

Foo is similarly defined:

   1:  public interface IFooService
   2:  {
   3:      IObservable<Unit> Generate();
   4:  }

The implementation of the Foo service is the important part, it uses the Boo service to generate a value, it's expected to generate the value or Timeout, if it fails to generate a value (for what ever reason) it's expected to to Retry:

   1:  public class FooService : IFooService
   2:  {
   3:      private readonly IBarService _barService;
   4:      private readonly IScheduler _scheduler;
   5:   
   6:      public FooService(IBarService barService, IScheduler scheduler)
   7:      {
   8:          _barService = barService;
   9:          _scheduler = scheduler;
  10:      }
  11:   
  12:      public IObservable<Unit> Generate()
  13:      {
  14:          return _barService.Generate()
  15:                            .Timeout(TimeSpan.FromSeconds(10), _scheduler)
  16:                            .Retry(5)
  17:                            .Select(bar => Unit.Default);
  18:      }
  19:  }

You can see I've set the time out to be 10 seconds and a maximum of 5 attempts...

So I wanted to put Timeout & Retry under test, to do this we use moq for mocking out our dependencies, we also use nCrunch for continuous testing, you'll see this in the screenshots below as the red\green icons on the left-hand side of the code - these icons tell me where the code is failing etc..

   1:  [Test]
   2:  public void should_timeout()
   3:  {
   4:      // ARRANGE
   5:      Exception exception = null;
   6:      var fooService = new FooService(_barService.Object, _testScheduler);
   7:   
   8:      // ACT
   9:      fooService.Generate()
  10:                .ObserveOn(_testScheduler)
  11:                .Subscribe(_ => { }, exn => exception = exn);
  12:   
  13:      _testScheduler.AdvanceBy(TimeSpan.FromHours(1).Ticks);
  14:   
  15:      // ASSERT
  16:      Assert.That(exception, Is.Not.Null);
  17:  }
  18:          
  19:  [Test]
  20:  public void should_retry()
  21:  {
  22:      // ARRANGE
  23:      Exception exception = null;
  24:      var fooService = new FooService(_barService.Object, _testScheduler);
  25:   
  26:      // ACT
  27:      fooService.Generate()
  28:                .ObserveOn(_testScheduler)
  29:                .Subscribe(_ => { }, exn => exception = exn);
  30:   
  31:      _testScheduler.AdvanceBy(TimeSpan.FromHours(1).Ticks);
  32:   
  33:      // ASSERT
  34:      Assert.That(_retryCount, Is.EqualTo(5));
  35:  }

As you can see two identical tests, asserting on different behaviours of the FooService, you'll notice the constructor of the FooService is being injected with an instance of the BarService, this is being created as Mock<T> of the IBarService interface.

You'll also notice the use of the MS TestScheduler for Rx, essential for unit testing anything in Rx.

So my first attempt at mocking this out looked like this:

   1:  [SetUp]
   2:  public void SetUp()
   3:  {
   4:      _testScheduler = new TestScheduler();
   5:   
   6:      _retryCount = 0;
   7:      _barService = new Mock<IBarService>();
   8:      _barService.Setup(x => x.Generate()).Returns(
   9:          () =>
  10:              {
  11:                  Debug.WriteLine("Retry {0}", ++_retryCount);
  12:                  return Observable.Never<Unit>();
  13:              });
  14:  }

When the tests were run I didn't expected either of the tests to fail, but what I got was one successful & one failed test! The Timeout had worked but the Retry schedule hadn't!
My initial thought was I hadn't passed the scheduler to the Rx Retry method in the FooService implementation, but after checking I realised it doesn't need take the scheduler so the problem must be with the test setup. To be more precise the problem must have been with what was being returned for the mocked Generate method on the IBarService.

This was indeed the problem, the mock should have been returning a Func which created an observable sequence which never pumps instead of what I initially had, a Func returning a sequence which never pumped:

   1:  [SetUp]
   2:  public void SetUp()
   3:  {
   4:      _testScheduler = new TestScheduler();
   5:   
   6:      _retryCount = 0;
   7:      _barService = new Mock<IBarService>();
   8:      _barService.Setup(x => x.Generate()).Returns(
   9:          () =>
  10:              {
  11:                  return Observable.Create<Unit>(o =>
  12:                  {
  13:                      Debug.WriteLine("Retry {0}", ++_retryCount);
  14:                      return Observable.Never<Unit>().Subscribe(o);                
  15:                  });
  16:              });
  17:  }

 The change is subtle but makes a big difference when testing:
Looking at the decompiled code it tells me why, the Retry extension method is using the Catch extension method to replace the faulted source stream with another, it just so happens that happens to be the source stream, so therefore from a mocking point of view you need to make sure that every time the Return Func is executed it creates a valid non-faulted stream.


Read More
Posted in Development, Mocking, Reactive Extensions, TDD | No comments

Sunday, 4 November 2012

Observable.Timer throws ArgumentOutOfRangeException

Posted on 05:24 by Unknown
We found this one out during testing in different time zones earlier this - if your app is going used in different time zones avoid using DateTime with Observable.Timer. In fact I guess the general message should be avoid DateTime all together in any apps use DateTimeOffset instead...

This code works from here in London but when run in Hong Kong throws an exception:

   1:  static void Main(string[] args)
   2:  {
   3:      var now = DateTimeOffset.Now;
   4:      Console.WriteLine("Time zone offset: " + now.Offset);
   5:   
   6:      var scheduler = NewThreadScheduler.Default;
   7:   
   8:      using(Observable.Timer(DateTime.MinValue, TimeSpan.FromSeconds(1), scheduler)
   9:          .Subscribe(Console.WriteLine))
  10:      {
  11:          Console.ReadLine();
  12:      }            
  13:  }

London time zone shows output as expected:
Where as when run for a time zone set to anything positive of London (offset = 0), e.g. Hong Kong (offset =  +8) you get an exception:
If you want to know why this is happening check out @leeoades post here, but simply because DateTime supports an implicit conversation to DateTimeOffset and the value is invalid after conversation this is why we're seeing this happen.

So it can be fixed easily enough by using any of the following alternatives:

   1:  Observable.Timer(DateTimeOffset.MinValue, TimeSpan.FromSeconds(1));
   2:   
   3:  // or...
   4:   
   5:  Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(1));
   6:   
   7:  // or...
   8:   
   9:  var scheduler = NewThreadScheduler.Default;
  10:  Observable.Timer(scheduler.Now, TimeSpan.FromSeconds(1), scheduler);

I prefer the final alternative, it's better suited for testing because the scheduler can be mocked out and you can control the value of the Scheduler.Now.
Read More
Posted in .Net, Development, Reactive Extensions | No comments

Wednesday, 31 October 2012

Trying to be more functional with Rx

Posted on 14:55 by Unknown
I realised this week I'm not being as functional when creating an Rx extension method as I should could be.

This came out of a discussion I was having with @leeoades about a Pausable<T> extension we thought we needed at work. Lee had a solution and I thought I'd try to create one without looking for the answer on the t'internet.

   1:  public static IObservable<T> Pausable<T>(this IObservable<T> stream,
                                                IObservable<bool> paused,
                                                bool initialState = false)
   2:  {
   3:      ...
   4:  }

Hopefully the idea of the method is obvious - have the ability to pause & resume the publishing of instances to the stream.

Before implementing Pausable<T> I thought I'd implement an extension that didn't remember state whilst paused - Suspendable<T>, as you can see the same signature.

   1:  public static IObservable<T> Suspendable<T>(this IObservable<T> stream,
                                                   IObservable<bool> suspend,
                                                   bool initialState = false)
   2:  {
   3:      ...
   4:  }

So my first attempt looked like this:

   1:  public static IObservable<T> Suspendable<T>(this IObservable<T> stream,
                                                   IObservable<bool> suspend,
                                                   bool initialState = false)
   2:  {
   3:      var suspended = new ReplaySubject<bool>(1);
   4:      suspended.OnNext(initialState);
   5:              
   6:      suspend.Subscribe(suspended.OnNext);
   7:      return stream.Where(t => !suspended.Take(1).Wait());
   8:  }

And to make sure this does exactly what's expected a set of tests covering all the edge cases:
Each of these test follow a common pattern with a defined generator publishing numbers to the Rx stream, 0 - 100. Shown below is the setup and a couple of the tests, one demonstrating a single resume and the other a multiple resume scenario:

   1:  [SetUp]
   2:  public void SetUp()
   3:  {
   4:      _generatorCount = 100;
   5:      _testScheduler = new TestScheduler();
   6:   
   7:      _generator = Observable.Generate(1,
   8:          x => x <= _generatorCount,
   9:          x => x + 1,
  10:          x => x,
  11:          x => TimeSpan.FromSeconds(1), _testScheduler);
  12:  }
  13:   
  14:  [Test]
  15:  public void should_recieve_values_after_single_resuming()
  16:  {
  17:      // ARRANGE
  18:      var count = 0;
  19:      var suspend = new Subject<bool>();
  20:   
  21:      _generator.Suspendable(suspend, true)
  22:          .Subscribe(n => count++);
  23:   
  24:      // ACT
  25:      _testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(1100).Ticks);
  26:      suspend.OnNext(false);
  27:      _testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(1010).Ticks);
  28:   
  29:      // ASSERT
  30:      Assert.That(count, Is.EqualTo(1));
  31:  }
  32:          
  33:  [Test]
  34:  public void should_recieve_values_after_multiple_resuming()
  35:  {
  36:      // ARRANGE
  37:      var count = 0;
  38:      var suspend = new Subject<bool>();
  39:   
  40:      _generator.Suspendable(suspend, true)
  41:          .Subscribe(n => count++);
  42:   
  43:      // ACT
  44:      _testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(10010).Ticks);
  45:      suspend.OnNext(false);
  46:      _testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(10010).Ticks);
  47:      suspend.OnNext(true);
  48:      _testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(10010).Ticks);
  49:      suspend.OnNext(false);
  50:      _testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(10010).Ticks);
  51:   
  52:      // ASSERT
  53:      Assert.That(count, Is.EqualTo(20));
  54:  }

So why is this implementation of Suspendable<T> not an ideal solution even though all the tests pass?

Subjects are mutable by design and from a functional programming perspective the idea of being able to mutate state is not something you want to do. Obviously you can use subjects, one scenario is where the subject is the origin of an Rx stream, e.g. in a service publishing instances asynchronously via the OnNext method. This isn't applicable in an Rx extension method. Ideally one should be using other Rx operators & extension methods.

A quick Google search for 'avoid Subject Rx' leads me to a post on the Rx forum by the Eric Meijer giving his view on the topic.

So how do I make this a more functional implementation?

The easiest way to avoid using a Subject<T> is to use a Observable.Create<T> to return the IObservable<T> instance, this is what I came up with:

   1:  public static IObservable<T> Suspendable<T>(this IObservable<T> stream,
                                                   IObservable<bool> suspend,
                                                   bool initialState = false)
   2:  {
   3:      return Observable.Create<T>(o =>
   4:      {
   5:          var disposable = suspend.StartWith(initialState)
   6:                  .DistinctUntilChanged()
   7:                  .Select(s => s ? Observable.Empty<T>() : stream)
   8:                  .Switch()
   9:                  .Subscribe(o);
  10:   
  11:          return disposable;
  12:      });
  13:  }

This introduced me to two new Rx operators - StartWith & Switch, StartWith should be obvious in what it does but Switch is a little more subtle, it only produces values from the latest observable stream. In the code above the Select operator returns the original observable stream or an empty observable stream depending on the suspend observable stream most recent value.

Now this implementation has an issue and because I'm a good programmer and already had unit tests it was picked up straight away :)
As you can see from the output the test 'should_complete_when_stream_completes' fails - hopefully the test name is obvious, but if not basically I'm expecting the OnComplete action to be called when the stream completes:
For some reason the completed parameter is never set to true and therefore the assert fails as shown by the red x shown at the side. The stream is setup as follows, you can see it completes when 100 is reached:

   1:  _generatorCount = 100;
   2:  _testScheduler = new TestScheduler();
   3:   
   4:  _generator = Observable.Generate(1,
   5:      x => x <= _generatorCount,
   6:      x => x + 1,
   7:      x => x,
   8:      x => TimeSpan.FromSeconds(1), _testScheduler);

What confuses me about this is the fact I have another test in which the generator throws an exception when the value of 42 is reached and this test passes:
So why isn't the OnComplete action ever called if the OnError action can be called?

I'm sure there's something missing  wrong with the implementation of my Suspend<T> extension method, I'll continue to investigate...
Read More
Posted in .Net, Development, Rx, TDD | No comments

Tuesday, 23 October 2012

Building a simple Portable Class Library - Simple.Rest

Posted on 13:45 by Unknown
I wanted to see how easy it was to build a Portable Class Library, and the answer is very easy. What follows is my experience.

First off create the project...
Next choose the platforms you want to support, you can changes these later via the project settings page:
At this point you're ready to start creating your masterpiece...

For this demo I thought I would revisit the WP7Contrib. Last year I built as part of the WP7Contrib a set of wrapper class around  HttpWebRequest & HttpWebResponse classes to make communicating with a RESTful web service easier - ResourceClient.

I was interested to see how this would turn out when implemented as a PCL. Also I was interested to see which framework features weren't supported for the selected target frameworks. I knew I wanted to use Task<T> for the asynchronous nature of my library's interface:

   1:  public interface IRestClient
   2:  {
   3:      Task<IRestResponse<T>> GetAsync<T>(Uri url) where T : class;
   4:   
   5:      Task<IRestResponse> PutAsync<T>(Uri url, T resource) where T : class;
   6:   
   7:      Task<IRestResponse<T>> PostAsync<T>(Uri url, T resource) where T : class;
   8:   
   9:      Task<IRestResponse> DeleteAsync(Uri url);
  10:  }

This turned out to be the first issue as Task is not supported out of the box for any of the current WP7 platforms or Silverlight 4. This materialises as build errors:
Can I get round this or does this mean I'm going to have to reduce the number of targeted frameworks?

This seems to be the main problem when building a PCL - the lack of support for certain language\framework features and working out what is and isn't supported.

Initially I was going to use the AsyncBridge package, it has a PCL version, but it only supports Silverlight 5.0 not 4.0. But then yesterday I saw this blog post about Using async/await without .NET Framework 4.5 and this covered all the targets I needed...

Adding the Microsoft.Bcl.Async package along with the Json.Net package I was able to get a successful build. You'll notice in the screenshot below showing the referenced assemblies - out of the box a PCL only has the a reference to .NET Portable Subset:
Testing my PCL was very easy and simple - no need to test on different frameworks, just a standard test library in 4.5 with a reference to nUnit and I was away.

This ability for me is probably the greatest feature of building a PCL for the simple reason being I can now write tests for a platform that is relatively hard to test for (e.g. WP7)  in away that can be incorporated into an automated build process. I've used Project Linker to do this before but compared to this that was a hassle:
And after implementing the PCL completely I get all the tests to sucessfully pass:
That pretty much covers my experience of building a simple PCL...

I've pushed this code up onto GitHub here and I also pushed out a NuGet package called Simple.Rest
Read More
Posted in .Net, Development, Portable Class Library | No comments

Wednesday, 17 October 2012

Tricky continuous testing and self hosting WebAPI issue...

Posted on 09:36 by Unknown
When using WebAPI inside a test fixture make sure you shutdown the HttpSelfHostServer instance correctly or your tests will more than likely fail when run from a continuous testing framework like nCrunch.

See this post for info about using the self hosting version of WebAPI inside a test fixture.

So my tests were running successfully when run inside Visual Studio from either the inbuilt runner or via Reshaper, but were failing when run from nCrunch:
The failing tests weren't consistent either, sometimes none would fail, sometimes a couple, sometimes all...

What the tests had in common was they were using a shared resource setup inside the test fixture setup method - this is like the setup method for a test but scoped at the class (test fixture) level. The setup was failing randomly were it was setting up the WebAPI self host - see highlighted yellow area, you can see the failing icon for nCrunch at the side:
The exception was telling me it was trying to create an instance of the service on a port already assigned:
So my first thought was because the tests for the fixture are being run in parallel then multiple instances of the fixture are trying to be created at the same time and therefore multiple registration attempts for the same port...

But after debugging the code with breakpoints for the SetUp & TearDown it appears this was wrong, these methods were only called once per run. This meant the service wasn't shutting down correctly when test execution had completed.

The TestService class is shown below. I thought I was shutting down the WebAPI host correctly by calling Dispose in the class Dispose method:

   1:  public class TestService : IDisposable
   2:  {
   3:      private readonly string _baseUrl;
   4:   
   5:      private HttpSelfHostServer _server;
   6:   
   7:      public IList<Employee> Employees;
   8:      public IList<Report> Reports;
   9:      public TimeSpan Delay;
  10:   
  11:      public TestService(string baseUrl)
  12:      {
  13:          _baseUrl = baseUrl;
  14:   
  15:          SetUpControllers();
  16:          SetUpHost();
  17:      }
  18:   
  19:      public void Dispose()
  20:      {
  21:          _server.Dispose();
  22:      }
  23:   
  24:      private void SetUpHost()
  25:      {
  26:          var config = new HttpSelfHostConfiguration(_baseUrl);
  27:   
  28:          config.Routes.MapHttpRoute("DefaultAPI", "api/{controller}/{id}", new { id = RouteParameter.Optional });
  29:   
  30:          _server = new HttpSelfHostServer(config);
  31:          _server.OpenAsync().Wait();
  32:      }
  33:   
  34:      private void SetUpControllers()
  35:      {
  36:          Employees = new List<Employee>
  37:          {  
  38:              new Employee { Id = 1, FirstName = "Ollie", LastName = "Riches" },
  39:              new Employee { Id = 2, FirstName = "Steve", LastName = "Austin" },
  40:          };
  41:   
  42:          EmployeesController.Employees = Employees;
  43:   
  44:          Delay = TimeSpan.FromSeconds(3);
  45:          Reports = new List<Report>
  46:          {  
  47:              new Report { Id = 1, Name = "SlowReport" }
  48:          };
  49:   
  50:          ReportsController.Delay = Delay;
  51:          ReportsController.Reports = Reports;
  52:      }
  53:  }

But this wasn't the case, after changing to the following all tests were passing as expected:

   1:  public void Dispose()
   2:  {
   3:      _server.CloseAsync().Wait();
   4:      _server.Dispose();
   5:  }

I had to re-initialising nCrunch to force any remaining service instances to shutdown:
I would have thought calling Dispose on HttpSelfHostServer would have meant it blocked until the server had shutdown but it appears not. Looking into the implementation it appears it doesn't close the server unless a task completion source had already been defined (also shown is the implementation for CloseAsync()):
I hope this helps if you run into this issue :)
Read More
Posted in C#, continuous testing, Development, TDD, unit testing, WebAPI | No comments

Sunday, 14 October 2012

Exception handling for an async method

Posted on 13:32 by Unknown
I've been unit testing a method which has a return type of Task<T> and I need to handle cases where  exceptions will be thrown.

Should I use the Task approach or convert to an Rx observable stream?

Task try-catch approach:
or Rx declarative style:
I know which one I prefer :)
Read More
Posted in Development, Exceptions, Rx, TPL | No comments

Saturday, 13 October 2012

Self hosting a web service inside a test fixture using WebAPI

Posted on 12:03 by Unknown
I have a class which handles all the communication to any back-end RESTful service, it wraps up all the complexity of using HttpWebRequest and provides a simple API:

   1:  public interface IRestClient
   2:  {
   3:      Task<RestResponse<T>> GetAsync<T>(Uri url) where T : class;
   4:      Task<RestResponse> PutAsync<T>(Uri url, T resource) where T : class;
   5:      Task<RestResponse<T>> PostAsync<T>(Uri url, T resource) where T : class;
   6:      Task<RestResponse> DeleteAsync(Uri url);
   7:  }

The implementation of this class isn't relevant for this post - it's all about the behaviour. The behaviour is what I'm trying to test not the internal implementation...

So how can I test this in a standard test fixture?

I knew it was possible but I didn't think it would so easy...

Having used asp.net WebAPI for hosting services in IIS I knew this was the tech stack I wanted to use, but could it be used to host a service inside a custom process - any of the popular testing frameworks?

The answer is yes, you have to use the Web API Self Host NuGet package and then you only need 5 lines of code to have a service up and running inside any process:

   1:  var config = new HttpSelfHostConfiguration(_baseUrl);
   2:   
   3:  config.Routes.MapHttpRoute("DefaultAPI", "api/{controller}/{id}", new { id = RouteParameter.Optional });
   4:   
   5:  _server = new HttpSelfHostServer(config);
   6:  _server.OpenAsync()
   7:      .Wait();

The only difference from the test fixture point of view was instead of using a setup & tear-down per test, it will be per test fixture - per class. In the example below I'm using nUnit but you should be able to doing the equivalent in all the common testing frameworks:
You can see I'm setting up a HTTP service on port 8083, I use the explicit machine name instead of localhost so that I can observe the HTTP traffic in Fiddler. When you've more than one test fixture using self hosting you're going to need a unique port for each test fixture - this means if you run the tests in parallel you won't get any port conflicts.

You can also see the test controller I'm using - EmployeesController, from a testing point of view the I don't care about the actual data just that it can be serialized and sent over the wire. The controller is shown below and it has methods to support the common HTTP verbs - GET, POST, PUT &  DELETE...

It exposes the employees as a public static property so I can set it from the test fixture:

   1:  public class EmployeesController : ApiController
   2:  {
   3:      public static IList<Employee> Employees = new List<Employee>();
   4:          
   5:      public IEnumerable<Employee> GetAllEmployees()
   6:      {
   7:          return Employees;
   8:      }
   9:   
  10:      public HttpResponseMessage Get(int id)
  11:      {
  12:          var testHeader = Request.Headers.FirstOrDefault(h => h.Key == "TestHeader");
  13:              
  14:          var cookies = Request.Headers.GetCookies();
  15:          var testCookie = cookies.FirstOrDefault(c => c.Cookies.Contains(new CookieState("TestCookie")));
  16:   
  17:          var employee = Employees.FirstOrDefault((p) => p.Id == id);
  18:          if (employee == null)
  19:          {
  20:              throw new HttpResponseException(HttpStatusCode.NotFound);
  21:          }
  22:   
  23:          var response = Request.CreateResponse(HttpStatusCode.OK, employee);
  24:   
  25:          if (testHeader.Key != null)
  26:          {
  27:              response.Headers.Add("TestHeader", testHeader.Value);
  28:          }
  29:   
  30:          if (testCookie != null)
  31:          {
  32:              response.Headers.AddCookies(new[] { new CookieHeaderValue("TestCookie", testCookie["TestCookie"].Value) });
  33:          }
  34:   
  35:          return response;
  36:      }
  37:   
  38:      public void Put(int id, Employee employee)
  39:      {
  40:          var existEmployee = Employees.FirstOrDefault((p) => p.Id == id);
  41:          if (existEmployee == null)
  42:          {
  43:              Employees.Add(employee);
  44:          }
  45:          else
  46:          {
  47:              existEmployee.FirstName = employee.FirstName;
  48:              existEmployee.LastName = employee.LastName;
  49:          }
  50:      }
  51:   
  52:      public HttpResponseMessage Post(Employee employee)
  53:      {
  54:          var maxId = Employees.Max(e => e.Id);
  55:          var newId = ++maxId;
  56:   
  57:          employee.Id = newId;
  58:          Employees.Add(employee);
  59:   
  60:          var uri = Url.Link("DefaultApi", new { id = employee.Id });
  61:   
  62:          var response = Request.CreateResponse(HttpStatusCode.Redirect);
  63:          response.Headers.Location = new Uri(uri);
  64:          return response;
  65:      }
  66:   
  67:      public HttpResponseMessage Delete(int id)
  68:      {
  69:          var existEmployee = Employees.FirstOrDefault(p => p.Id == id);
  70:          if (existEmployee != null)
  71:          {
  72:              Employees.Remove(existEmployee);
  73:          }
  74:   
  75:          return new HttpResponseMessage(HttpStatusCode.NoContent);
  76:      }
  77:  }

So now I'm able to have a nice clean unit test:

   1:  [Test]
   2:  public void should_return_single_json_object()
   3:  {
   4:      // ARRANGE
   5:      var url = new Uri(_baseUrl + "/api/employees/1");
   6:   
   7:      // ACT
   8:      var task = _restClient.GetAsync<Employee>(url);
   9:      task.Wait();
  10:              
  11:      var employee = task.Result.Resource;
  12:              
  13:      // ASSIGN
  14:      Assert.That(employee, Is.Not.Null);
  15:      Assert.That(employee.Id, Is.EqualTo(_employees.First().Id));
  16:      Assert.That(employee.FirstName, Is.EqualTo(_employees.First().FirstName));
  17:      Assert.That(employee.LastName, Is.EqualTo(_employees.First().LastName));
  18:  }

And this gives the satisfying test output:
One thing to note is the setup of the service infrastructure takes sometime, this can been seen in the duration of the test 1.866 seconds. This only appears to apply to the first test fixture setup, shown below is the duration for 4 different test fixtures, each fixture has it's own service:
As you can see only the RestClient_DeleteTests takes any noticeable time to run...

So you can see it was relatively easy to get up and running, in fact it took less than 5 minutes...
Read More
Posted in Development, RESTful, testing, Web Services, WebAPI | No comments

Using GetRequestStreamAsync and GetResponseAsync in .Net 4.0 Portable Class Library

Posted on 09:48 by Unknown
I've been building a small Portable Class Library and it makes use of the WebRequest class. I'm targeting .Net 4.0 (and above), Silverlight 5 and Windows App Store. I would target the phone as well but it doesn't support the TPL at the moment - WP8 is just around the corner:
I wanted to use async method GetRequestStreamAsync  & GetResponseAsync but these aren't supported in .Net 4.0 and when creating a Portable Class Library you only get the commonly supported methods across the configured platforms - so no support then or may be not...

Why not just create a couple of extension methods?

   1:  public static class HttpWebRequestExtensions
   2:  {
   3:      public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request)
   4:      {
   5:          var tcs = new TaskCompletionSource<Stream>();
   6:   
   7:          try
   8:          {
   9:              request.BeginGetRequestStream(iar =>
  10:              {
  11:                  try
  12:                  {
  13:                      var response = request.EndGetRequestStream(iar);
  14:                      tcs.SetResult(response);
  15:                  }
  16:                  catch (Exception exc)
  17:                  {
  18:                      tcs.SetException(exc);
  19:                  }
  20:              }, null);
  21:          }
  22:          catch (Exception exc)
  23:          {
  24:              tcs.SetException(exc);
  25:          }
  26:   
  27:          return tcs.Task;
  28:      }
  29:   
  30:      public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
  31:      {
  32:          var tcs = new TaskCompletionSource<HttpWebResponse>();
  33:   
  34:          try
  35:          {
  36:              request.BeginGetResponse(iar =>
  37:              {
  38:                  try
  39:                  {
  40:                      var response = (HttpWebResponse)request.EndGetResponse(iar);
  41:                      tcs.SetResult(response);
  42:                  }
  43:                  catch (Exception exc)
  44:                  {
  45:                      tcs.SetException(exc);
  46:                  }
  47:              }, null);
  48:          }
  49:          catch (Exception exc)
  50:          {
  51:              tcs.SetException(exc);
  52:          }
  53:   
  54:          return tcs.Task;
  55:      }
  56:  }

When used with the AsyncBridge NuGet package to provide async support in .Net 4.0 \ Silverlight 5 you get exactly the same syntax as if this was a standard .Net 4.5 library:

Read More
Posted in .Net 4.5, Async, Developement, Portable Library, TPL | No comments

Tuesday, 9 October 2012

Testing time based observable in Rx is so easy...

Posted on 09:12 by Unknown
If you've been doing Rx for a while it's very likely you're also be into testing with TDD. In which case you'll have come across testing observable timers but if not then what follows is how easy this is.

So lets say I want to test the following method, it generates a 'tick' according to the time span parameter:

   1:  public IObservable<Unit> TickEvery(TimeSpan timeSpan)
   2:  {
   3:      return Observable.Interval(timeSpan).TimeInterval()
   4:          .Select(_ => new Unit());
   5:  }

When testing this I don't want to be dependent on the scheduler clock, what I mean is you don't want the test code to have to do some kind of 'wait' operation whilst the Observable.Interval is generating values.

The answer is to use the Reactive Extensions Testing Library. It provides the TestScheduler which allows to manipulate the underlying clock using the AdvanceBy & AdvanceTo methods which then means you can trigger any observable timer in a timely manner!

This means you do have to use the overloaded Observable.Interval to pass the scheduler to the method, I've wrapped the method into a class and I'm using DI to pass in the scheduler:

   1:  public class MyTicker
   2:  {
   3:      private readonly IScheduler _scheduler;
   4:   
   5:      public MyTicker(IScheduler scheduler)
   6:      {
   7:          _scheduler = scheduler;
   8:      }
   9:   
  10:      public IObservable<Unit> TickEvery(TimeSpan timeSpan)
  11:      {
  12:          return Observable.Interval(timeSpan, _scheduler).TimeInterval()
  13:              .Select(_ => new Unit());
  14:      }
  15:  }

So now I need a test, I want to simulate generating ticks every minute and I want to receive only 2 ticks:

   1:  [TestFixture]
   2:  public class MyTickerTests
   3:  {
   4:      private long _minuteInTicks;
   5:      private TestScheduler _scheduler;
   6:   
   7:      [SetUp]
   8:      public void SetUp()
   9:      {
  10:          // a minute in ticks...
  11:          _minuteInTicks = new TimeSpan(0, 0, 1, 0).Ticks;
  12:   
  13:          // this is the important bit...
  14:          _scheduler = new TestScheduler();
  15:      }
  16:          
  17:      [Test]
  18:      public void should_tick_twice_in_three_minutes()
  19:      {
  20:          // ARRANGE
  21:          var ticker = new MyTicker(_scheduler);
  22:          var tickInternval = TimeSpan.FromMinutes(1);
  23:          var count = 0;
  24:              
  25:          // ACT
  26:          using (ticker.TickEvery(tickInternval)
  27:              .Subscribe(_ => count++))
  28:          {
  29:              _scheduler.AdvanceBy(_minuteInTicks);
  30:              _scheduler.AdvanceBy(_minuteInTicks);
  31:          }
  32:   
  33:          _scheduler.AdvanceBy(_minuteInTicks);
  34:   
  35:          // ASSERT
  36:          Assert.AreEqual(count, 2, "the count should have only been incremented twice...");
  37:      }
  38:  }

Which passes as expected...


Read More
Posted in Async, Development, Rx, TDD, testing | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • Unit testing Rx methods Timeout & Retry with moq
    Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
  • Understanding RefCount in Reactive Extensions
    A couple of weeks ago  @LordHanson  & I ran into an issue converting a stateless async service exposed as an Rx cold observable to a  co...
  • StructureMap: ILifecycle
    The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextS...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • How many pins can Bing Maps handle in a WP7 app - part 1
    part2 -  http://awkwardcoder.blogspot.com/2011/10/how-many-pins-can-bing-maps-handle-in.html part3 -  http://awkwardcoder.blogspot.com/2011/...
  • Bad developers love 'The Daily WTF'
    When 'The Daily WTF' started up back in 2003/2004 it was a great laugh looking at shocking code other developers wrote, but after a ...
  • Using CompositeDisposable in base classes
    To help make an object eligible for collection by the GC (garbage collector) one would implement the IDisposable interface. Executing the di...
  • Implementing a busy indicator using a visual overlay in MVVM
    This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whil...
  • Daily Dilbert Service - the most important service I've ever written...
    NuGet package available here ... First off a big shout to  @hamish  &  @leeoades  on this one - I'm just blogging about it. At work ...
  • Comparing performance of .Net 4.5 to .Net 4.0 for WPF
    Currently I'm working on a .Net 4.0 WPF app and we've had some discussion about moving to .Net 4.5, we don't get to make the dec...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ►  2013 (16)
    • ►  November (5)
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ▼  2012 (44)
    • ▼  November (2)
      • Unit testing Rx methods Timeout & Retry with moq
      • Observable.Timer throws ArgumentOutOfRangeException
    • ►  October (8)
      • Trying to be more functional with Rx
      • Building a simple Portable Class Library - Simple....
      • Tricky continuous testing and self hosting WebAPI ...
      • Exception handling for an async method
      • Self hosting a web service inside a test fixture u...
      • Using GetRequestStreamAsync and GetResponseAsync i...
      • Testing time based observable in Rx is so easy...
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ►  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ►  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ►  September (11)
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile