0 day streak
csharp / expert
Snippet

Isolated Unit Testing via Delegate Injection

For expert-level decoupling without the overhead of heavy DI frameworks or interfaces, delegates can be used as injection points. This makes unit testing trivial as you can pass simple lambdas as 'mocks', ensuring that functions remain pure and easily testable in isolation.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Calculator
{
// Define a delegate for a dependency that would normally be an interface
public delegate int DataSource();
public int AddFromSource(DataSource source, int b)
{
return source() + b;
}
}
// Usage in a Test Scenario
public static class CalculatorTests
{
public static void RunTest()
{
var calc = new Calculator();
// Mocking without a framework: simply pass a lambda
int result = calc.AddFromSource(() => 10, 5);
if (result != 15) throw new Exception("Test Failed!");
}
}
Breakdown
1
public delegate int DataSource()
Defines a contract for a data dependency using a functional signature instead of an interface.
2
calc.AddFromSource(() => 10, 5)
Injects a hardcoded value directly into the logic for verification, avoiding external state.