csharp / expert
Snippet
Isolierte Unit-Tests durch Delegate-Injection
Für eine Entkopplung auf Expertenniveau ohne den Overhead schwerer DI-Frameworks oder Interfaces können Delegates als Injection-Points genutzt werden. Dies macht Unit-Tests trivial, da einfache Lambdas als 'Mocks' übergeben werden können, wodurch Funktionen pur und isoliert testbar bleiben.
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 interfacepublic delegate int DataSource();public int AddFromSource(DataSource source, int b){return source() + b;}}// Usage in a Test Scenariopublic static class CalculatorTests{public static void RunTest(){var calc = new Calculator();// Mocking without a framework: simply pass a lambdaint result = calc.AddFromSource(() => 10, 5);if (result != 15) throw new Exception("Test Failed!");}}
Erklärung
1
public delegate int DataSource()
Definiert einen Vertrag für eine Datenabhängigkeit mittels funktionaler Signatur anstelle eines Interfaces.
2
calc.AddFromSource(() => 10, 5)
Injiziert einen festkodierten Wert direkt in die Logik zur Verifizierung, ohne externen Status.