csharp / expert
Snippet
Manual Mocking via Interface Delegate Stubs
Expert-level unit testing often avoids complex mocking frameworks to reduce overhead and improve test speed. By creating a 'stub' implementation of an interface where methods call public delegates, you can easily inject custom behavior directly within your test methods.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface IUserRepository{string GetUsername(int id);}// Manual mock for testing without librariespublic class MockUserRepository : IUserRepository{public Func<int, string> GetUsernameStub = _ => "Default";public string GetUsername(int id) => GetUsernameStub(id);}// Test usagevar mock = new MockUserRepository { GetUsernameStub = id => "TestUser" };
Breakdown
1
public Func<int, string> GetUsernameStub
A field that holds the logic for the method, allowing it to be swapped out per test case.
2
GetUsernameStub = id => "TestUser"
Injects specific test behavior into the mock during the 'Arrange' phase of a test.