SourceMock
SourceMock copied to clipboard
SourceMock is a C# mocking framework based on source generators
Overview
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)
Cookbook
All examples assume the following interface:
namespace Parsing {
interface IParser { int Parse(string value); }
}
Set up a simple mock
[assembly: GenerateMocksForAssemblyOf(typeof(IParser))]
using Parsing.Mocks;
var parser = new ParserMock();
parser.Setup.Parse().Returns(1);
Assert.Equal(1, parser.Parse());
Verify calls
[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());
Set up a callback
[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"));
Limitations
By Design
Strict Mocks
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.
Not Yet
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
Kudos
This framework borrows a lot of its design from Moq, which is one of the best .NET libraries overall.