public interface IFoo
{
int Bar(bool b);
}
var mock = new Mock<IFoo>();
mock.Setup(mc => mc.Bar(It.IsAny<bool>()))
.Callback<bool>(b => Console.WriteLine("Bar called with: " + b))
.Returns(42);
var ret = mock.Object.Bar(true);
Console.WriteLine("Result: " + ret);
// output:
// Bar called with: True
// Result: 42
public class SystemUnderTest
{
private readonly Repository _repository;
public SystemUnderTest(Repository repository)
{
_repository = repository;
}
public void Add(int a, int b)
{
int result = a + b;
_repository.StoreResult(result);
}
}
public class Repository
{
public void StoreResult(int result)
{
// stores the result in the database
}
}
using Moq;
using Xunit;
namespace TestLocal.Tests;
public class CallbackTest
{
private readonly SystemUnderTest _sut;
private readonly Mock<Repository> _repository;
public CallbackTest()
{
_repository = new Mock<Repository>(MockBehavior.Strict);
_sut = new SystemUnderTest(_repository.Object);
}
[Fact]
public void AddTest()
{
int a = 1;
int b = 2;
int result = -1;
_repository.Setup(x => x.StoreResult(3))
.Callback<int>(callbackResult => result = callbackResult)
.Verifiable();
_sut.Add(a,b);
Assert.Equal(a+b, result);
}
}