SourceMock is a C# mocking framework based on source generators.
This allows for a nicer interface than reflection based frameworks, for example:
mock.Setup.Parse().Returns(3);
instead of
mock.Setup(x => x.Parse(It.IsAny<string>())).Return(3)
All examples assume the following interface:
namespace Parsing {
interface IParser { int Parse(string value); }
}
[assembly: GenerateMocksForAssemblyOf(typeof(IParser))]
using Parsing.Mocks;
var parser = new ParserMock();
parser.Setup.Parse().Returns(1);
Assert.Equal(1, parser.Parse());
[assembly: GenerateMocksForAssemblyOf(typeof(IParser))]
using Parsing.Mocks;
var parser = new ParserMock();
parser.Parse("1");
parser.Parse("2");
Assert.Equal(new[] { "1", "2" }, parser.Calls.Parse());
[assembly: GenerateMocksForAssemblyOf(typeof(IParser))]
using Parsing.Mocks;
var parser = new ParserMock();
parser.Setup.Parse().Runs(s => int.Parse(s));
Assert.Equal(1, parser.Parse("1"));
SourceMock does not provide strict mocks — this is by design.
I believe that verifying setups blurs the line between Arrange and Assert and decreases test readability.
Instead, assert .Calls
at the end of the test to confirm the expected calls.
These are not intentionally excluded, just not yet supported:
- Class mocks: custom constructors, calling base methods, mocking protected members
- Custom default values
- Custom parameter matchers
- Setting up output values for ref and out parameters
- Chained setups
- Anything more advanced than the above
This framework borrows a lot of its design from Moq, which is one of the best .NET libraries overall.