Created
January 3, 2014 09:46
-
-
Save HEskandari/8235481 to your computer and use it in GitHub Desktop.
NSubstitute and Async
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Threading.Tasks; | |
using NSubstitute; | |
using NUnit.Framework; | |
namespace ClassLibrary1 | |
{ | |
public interface ICalculationServiceAsync | |
{ | |
Task Calculate(); | |
} | |
public class SystemUnderTest | |
{ | |
private readonly ICalculationServiceAsync _service; | |
public SystemUnderTest(ICalculationServiceAsync service) | |
{ | |
_service = service; | |
} | |
public async void DoSomethingAsync() | |
{ | |
await _service.Calculate(); | |
} | |
} | |
[TestFixture] | |
public class AsyncTest | |
{ | |
[Test] | |
public void Can_await_on_async_mocks() | |
{ | |
var mockService = Substitute.For<ICalculationServiceAsync>(); | |
var sut = new SystemUnderTest(mockService); | |
sut.DoSomethingAsync(); | |
mockService.Calculate().ReceivedCalls(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
await
ing on the method projected byReceived()
will be a bit of a fail -- that projection returns null, so await throws a null dereference exception as it's trying to do something with the resultant task. So don't do (1).(2) is arduous -- traversing the
ReceivedCalls()
output collection and doing the work for NSubstitute is, well, arduous. I'd recommend another approach over (2): take advantage ofReceived.InOrder
:Or a shorter form without the braces. Since you probably had to mock out a resolved task to return from the
Calculate
method, this works just fine -- and you can easily use other NSubstitute constructs likeArg.Any<T>()
without having to futz about withRecievedCalls()
. Hope this helps (: