Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using FluentAssertions;
- using Moq;
- using System;
- using System.Threading.Tasks;
- using Xunit;
- namespace MyUnitTestProject
- {
- public interface IMyInterface
- {
- int CoolNumber();
- Task<int> CoolNumberAsync();
- }
- public class MyUnitTests
- {
- [Fact(DisplayName = "SetupSequence should return different results for subsequent calls")]
- public void SetupSequence_DifferentResults()
- {
- int expectedFirst = 5;
- int expectedSecond = 10;
- var myMock = new Mock<IMyInterface>();
- // Each subsequent call to the method will return the next link in the chain
- myMock.SetupSequence(m => m.CoolNumber())
- .Returns(expectedFirst)
- .Returns(expectedSecond);
- var first = myMock.Object.CoolNumber();
- var second = myMock.Object.CoolNumber();
- first.Should().Be(expectedFirst);
- second.Should().Be(expectedSecond);
- }
- [Fact(DisplayName = "SetupSequence should return different results for subsequent calls, even throwing exceptions!")]
- public void SetupSequence_FirstException()
- {
- bool firstExceptionThrown = false;
- int expectedSecond = 10;
- var myMock = new Mock<IMyInterface>();
- // Works with throwing exceptions, too
- myMock.SetupSequence(m => m.CoolNumber())
- .Throws(new Exception("Something bad happened!"))
- .Returns(expectedSecond);
- try
- {
- var first = myMock.Object.CoolNumber();
- }
- catch (Exception)
- {
- firstExceptionThrown = true;
- }
- var second = myMock.Object.CoolNumber();
- firstExceptionThrown.Should().BeTrue();
- second.Should().Be(expectedSecond);
- }
- [Fact(DisplayName = "SetupSequence should return different results for subsequent async calls")]
- public async Task SetupSequence_Async_DifferentResults()
- {
- int expectedFirst = 5;
- int expectedSecond = 10;
- var myMock = new Mock<IMyInterface>();
- // If you have an async method, that's no problem
- myMock.SetupSequence(m => m.CoolNumberAsync())
- .ReturnsAsync(expectedFirst)
- .ReturnsAsync(expectedSecond);
- var first = await myMock.Object.CoolNumberAsync();
- var second = await myMock.Object.CoolNumberAsync();
- first.Should().Be(expectedFirst);
- second.Should().Be(expectedSecond);
- }
- [Fact(DisplayName = "SetupSequence should return different results for subsequent async calls, even throwing exceptions!")]
- public async Task SetupSequence_Async_FirstException()
- {
- bool firstExceptionThrown = false;
- int expectedSecond = 10;
- var myMock = new Mock<IMyInterface>();
- // Async throwing of exceptions, too.
- myMock.SetupSequence(m => m.CoolNumberAsync())
- .ThrowsAsync(new Exception("Something bad happened!"))
- .ReturnsAsync(expectedSecond);
- try
- {
- var first = await myMock.Object.CoolNumberAsync();
- }
- catch (Exception)
- {
- firstExceptionThrown = true;
- }
- var second = await myMock.Object.CoolNumberAsync();
- firstExceptionThrown.Should().BeTrue();
- second.Should().Be(expectedSecond);
- }
- }
- }
Add Comment
Please, Sign In to add comment