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
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)
    • ►  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