-
-
Save anonymous/e5a74ce58e0f39f0372cf303ee5daa3c to your computer and use it in GitHub Desktop.
Example code illustrating how to unit test if a call is awaited
This file contains 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 Moq; | |
using NUnit.Framework; | |
namespace UnitTestingAsyncAwait | |
{ | |
public interface IUserRepository | |
{ | |
Task CreateNewUser(); | |
} | |
public interface IMessageDispatcher | |
{ | |
void DispatchEmailVerificationMessage(); | |
} | |
[TestFixture] | |
public class Demo | |
{ | |
private UserRegistrator _classUnderTest; | |
private Mock<IUserRepository> _userRepositoryMock; | |
private Mock<IMessageDispatcher> _messageDispatcherMock; | |
[SetUp] | |
public void SetUp() | |
{ | |
_userRepositoryMock = new Mock<IUserRepository>(); | |
_messageDispatcherMock = new Mock<IMessageDispatcher>(); | |
_classUnderTest = new UserRegistrator(_userRepositoryMock.Object, _messageDispatcherMock.Object); | |
} | |
[Test] | |
public void AwaitsAsyncCall() | |
{ | |
// Arrange | |
var tcs = new TaskCompletionSource<bool>(); | |
var task = tcs.Task; | |
_userRepositoryMock.Setup(a => a.CreateNewUser()).Returns(task); | |
// Act | |
_classUnderTest.Register(); | |
// Assert | |
_userRepositoryMock.Verify(a => a.CreateNewUser(), Times.Once); | |
_messageDispatcherMock.Verify(s => s.DispatchEmailVerificationMessage(), Times.Never, "Did not await the async thing."); | |
tcs.SetResult(true); //NOTE: The actual value is not relevant for this test but needed since there is no Task<void> in .Net. | |
_messageDispatcherMock.Verify(s => s.DispatchEmailVerificationMessage(), Times.Once); | |
} | |
} | |
public class UserRegistrator | |
{ | |
private readonly IUserRepository _userRepository; | |
private readonly IMessageDispatcher _messageDispatcher; | |
public UserRegistrator(IUserRepository userRepository, IMessageDispatcher messageDispatcher) | |
{ | |
_userRepository = userRepository; | |
_messageDispatcher = messageDispatcher; | |
} | |
public async Task Register() | |
{ | |
await _userRepository.CreateNewUser(); | |
_messageDispatcher.DispatchEmailVerificationMessage(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment