Thursday 18 September 2014

How to Setup Async and Task Return methods with Moq 4.2

Moq 4.2 comes with a couple of nice changes that I hadn't noticed (and they are extension methods, so you might continue to miss them)

The main benefit is allowing you to change from writing
 _mock.Setup(m => m.GetStateAsync(It.IsAny<Profile>()))   
 .Returns(Task.FromResult(new IndexDefinitionState(true, true)));  

to writing

  _mock.Setup(m=>m.GetStateFromStore(It.IsAny<Profile>()))  
    .ReturnsAsync(new IndexDefinitionState(true, true));  

...which is just that little bit easier to manage (especially when it is a more complex return type than the example above), but it also allows methods with return type Task to work without further setup it seems. Both are extremely useful for the Async-first API I'm working on.

From the release notes for Moq 4.2
  • Improved support for async APIs by making default value a completed task
  • Added support for async Returns and Throws
  • Improved mock invocation sequence testing

All great stuff. I really couldn't do without Moq - a long time back it was the thing that made me realise that unit testing was actually viable.

No comments:

Post a Comment