0 day streak
csharp / intermediate
Snippet

Isolation Testing with Functional Delegates

By passing a delegate like Func<string, bool> into a method, you can decouple the validation logic from the execution logic. This pattern makes unit testing easier as you can pass 'mock' behaviors without a full framework.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Processor
{
public bool Execute(string input, Func<string, bool> validator)
{
if (!validator(input)) return false;
// Process logic
return true;
}
}
// Usage in testing context
var processor = new Processor();
bool result = processor.Execute("test", s => s.Length > 2);
Breakdown
1
Func<string, bool> validator
A delegate representing a function that takes a string and returns a boolean.
2
if (!validator(input))
Invokes the passed delegate to determine if processing should continue.
3
s => s.Length > 2
A lambda expression passed as a specific validation strategy during testing.