Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.
NSubstitute Test Double Guide
Applicable Scenarios
This skill focuses on creating and managing test doubles using NSubstitute, covering the five types of Test Doubles,
dependency isolation strategies, behavior setup and validation best practices.
Why Do We Need Test Doubles?
Real-world code usually depends on external resources, which make tests:
- Slow - Need actual database operations, file systems, networks
- Unstable - External service failures cause test failures
- Difficult to Repeat - Time, random numbers cause inconsistent results
- Environment Dependent - Need specific external environment setup
- Development Blocking - Must wait for external systems to be ready
Test doubles allow us to isolate these dependencies and focus on testing business logic.
Prerequisites
Package Installation
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="AwesomeAssertions" Version="9.1.0" />
```text
### Basic using Directives
```csharp
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Xunit;
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
```text
## Test Double Five Types
According to Gerard Meszaros's definition in "xUnit Test Patterns", test doubles are divided into five types:
| Type | Purpose | NSubstitute Equivalent |
|------|------|-------------------|
| **Dummy** | Fill objects, only satisfy method signatures | `Substitute.For<T>()` without setting any behavior |
| **Stub** | Provide default return values, set test scenarios | `.Returns(value)` |
| **Fake** | Simplified implementation with real logic | Manual interface implementation (like `FakeUserRepository`) |
| **Spy** | Record calls, verify afterwards | `.Received()` validation |
| **Mock** | Default expected interactions, test fails if not satisfied | `.Received(n)` strict validation |
> Full code examples for each type please refer to [references/test-double-types.md](references/test-double-types.md)
## NSubstitute Core Functions
### Basic Substitution Syntax
```csharp
// Create interface substitute
var substitute = Substitute.For<IUserRepository>();
// Create class substitute (needs virtual members)
var classSubstitute = Substitute.For<BaseService>();
// Create multiple interface substitute
var multiSubstitute = Substitute.For<IService, IDisposable>();
```text
### Return Value Setup
#### Basic Return Values
```csharp
// Exact parameter matching
_repository.GetById(1).Returns(new User { Id = 1, Name = "John" });
// Any parameter matching
_service.Process(Arg.Any<string>()).Returns("processed");
// Return sequence values
_generator.GetNext().Returns(1, 2, 3, 4, 5);
```text
#### Conditional Return Values
```csharp
// Use delegate to calculate return value
_calculator.Add(Arg.Any<int>(), Arg.Any<int>())
.Returns(x => (int)x[0] + (int)x[1]);
// Condition matching
_service.Process(Arg.Is<string>(x => x.StartsWith("test")))
.Returns("test-result");
```text
#### Throw Exceptions
```csharp
// Synchronous method throws exception
_service.RiskyOperation()
.Throws(new InvalidOperationException("Something went wrong"));
// Async method throws exception
_service.RiskyOperationAsync()
.Throws(new InvalidOperationException("Async operation failed"));
```text
### Argument Matchers
```csharp
// Any value
_service.Process(Arg.Any<string>()).Returns("result");
// Specific condition
_service.Process(Arg.Is<string>(x => x.Length > 5)).Returns("long-result");
// Argument capture
string capturedArg = null;
_service.Process(Arg.Do<string>(x => capturedArg = x)).Returns("result");
_service.Process("test");
capturedArg.Should().Be("test");
// Argument check
_service.Process(Arg.Is<string>(x =>
{
x.Should().StartWith("prefix");
return true;
})).Returns("result");
```text
### Call Verification
```csharp
// Verify was called (at least once)
_service.Received().Process("test");
// Verify call count
_service.Received(2).Process(Arg.Any<string>());
// Verify was not called
_service.DidNotReceive().Delete(Arg.Any<int>());
// Verify any argument call
_service.ReceivedWithAnyArgs().Process(default);
// Verify call order
Received.InOrder(() =>
{
_service.Start();
_service.Process();
_service.Stop();
});
```text
## Practical Patterns
Covers five common NSubstitute practical patterns, including complete code examples:
| Pattern | Description |
|------|------|
| Pattern 1: Dependency Injection and Test Setup | FileBackupService complete example, including constructor injection and SUT setup |
| Pattern 2: Mock vs Stub Differences | Stub focuses on state return values vs Mock focuses on interaction behavior validation |
| Pattern 3: Async Method Testing | `Returns(Task.FromResult(...))` and `.Throws()` patterns |
| Pattern 4: ILogger Validation | Validate underlying `Log` method bypassing extension method limitations |
| Pattern 5: Complex Setup Management | Base test class managing shared Substitute setups |
> Full code examples please refer to [references/practical-patterns.md](references/practical-patterns.md)
## Advanced Argument Matching Techniques
### Complex Object Matching
```csharp
[Fact]
public void CreateOrder_CreateOrder_ShouldStoreCorrectOrderData()
{
var repository = Substitute.For<IOrderRepository>();
var service = new OrderService(repository);
service.CreateOrder("Product A", 5, 100);
// Verify object properties
repository.Received(1).Save(Arg.Is<Order>(o =>
o.ProductName == "Product A" &&
o.Quantity == 5 &&
o.Price == 100));
}
```text
### Argument Capture and Validation
```csharp
[Fact]
public void RegisterUser_RegisterUser_ShouldGenerateCorrectHashPassword()
{
var repository = Substitute.For<IUserRepository>();
var service = new UserService(repository);
User capturedUser = null;
repository.Save(Arg.Do<User>(u => capturedUser = u));
service.RegisterUser("john@example.com", "password123");
capturedUser.Should().NotBeNull();
capturedUser.Email.Should().Be("john@example.com");
capturedUser.PasswordHash.Should().NotBe("password123"); // Should be hashed
capturedUser.PasswordHash.Length.Should().BeGreaterThan(20);
}
```text
## Common Pitfalls and Best Practices
### Recommended Practices
1. **Target interfaces rather than implementations for Substitutes**
```csharp
// Correct: target interface
var repository = Substitute.For<IUserRepository>();
// Wrong: target concrete class (unless has virtual members)
var repository = Substitute.For<UserRepository>();
```text
2. **Use meaningful test data**
```csharp
// Correct: clearly express intent
var user = new User { Id = 123, Name = "John Doe", Email = "john@example.com" };
// Wrong: meaningless data
var user = new User { Id = 1, Name = "test", Email = "a@b.c" };
```text
3. **Avoid over-verification**
```csharp
// Correct: only verify important behaviors
_emailService.Received(1).SendWelcomeEmail(Arg.Any<string>());
// Wrong: verify all internal implementation details
_repository.Received(1).GetById(123);
_repository.Received(1).Update(Arg.Any<User>());
_validator.Received(1).Validate(Arg.Any<User>());
```text
4. **Clear distinction between Mock and Stub**
```csharp
// Correct: Stub for setting scenarios, Mock for validating behaviors
var stubRepository = Substitute.For<IUserRepository>(); // Stub
var mockLogger = Substitute.For<ILogger>(); // Mock
stubRepository.GetById(123).Returns(user);
service.ProcessUser(123);
mockLogger.Received(1).LogInformation(Arg.Any<string>());
```text
### Practices to Avoid
1. **Avoid simulating value types**
```csharp
// Wrong: DateTime is value type
var badDate = Substitute.For<DateTime>();
// Correct: abstract time provider
var dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.Now.Returns(new DateTime(2024, 1, 1));
```text
2. **Avoid tight coupling between tests and implementations**
```csharp
// Wrong: test implementation details
_repository.Received(1).Query(Arg.Any<string>());
_repository.Received(1).Filter(Arg.Any<Expression<Func<User, bool>>>());
// Correct: test behavior results
var users = service.GetActiveUsers();
users.Should().HaveCount(2);
```text
3. **Avoid overly complex setups**
```csharp
// Wrong: too many Substitutes (may violate SRP)
var sub1 = Substitute.For<IService1>();
var sub2 = Substitute.For<IService2>();
var sub3 = Substitute.For<IService3>();
var sub4 = Substitute.For<IService4>();
// Correct: reconsider class responsibilities
// Consider whether violating single responsibility principle, needs refactoring
```text
## Identifying Dependencies to Substitute
### Should Substitute
- External API calls (IHttpClient, IApiClient)
- Database operations (IRepository, IDbContext)
- File system operations (IFileSystem)
- Network communication (IEmailService, IMessageQueue)
- Time dependencies (IDateTimeProvider, TimeProvider)
- Random number generation (IRandom)
- Expensive calculations (IComplexCalculator)
- Logging services (ILogger<T>)
### Should Not Substitute
- Value objects (DateTime, string, int)
- Simple data transfer objects (DTO)
- Pure function tools (like AutoMapper's IMapper, consider using real instance)
- Framework core classes (unless explicitly needed)
## Troubleshooting
### Q1: How to test classes without interfaces?
**A:** Ensure members to be simulated are virtual:
```csharp
public class BaseService
{
public virtual string GetData() => "real data";
}
var substitute = Substitute.For<BaseService>();
substitute.GetData().Returns("test data");
```text
### Q2: How to verify method call order?
**A:** Use Received.InOrder():
```csharp
Received.InOrder(() =>
{
_service.Start();
_service.Process();
_service.Stop();
});
```text
### Q3: How to handle out parameters?
**A:** Use Returns() with delegate:
```csharp
_service.TryGetValue("key", out Arg.Any<string>())
.Returns(x =>
{
x[1] = "value";
return true;
});
```text
### Q4: NSubstitute vs Moq which to choose?
**A:** NSubstitute advantages:
- More concise and intuitive syntax
- Gentle learning curve
- No privacy controversies
- Sufficient for most testing scenarios
Choose NSubstitute, unless:
- Project already uses Moq
- Need Moq-specific advanced features
- Team already familiar with Moq syntax
## Integration with Other Skills
This skill can be combined with the following skills:
- **unit-test-fundamentals**: Unit test fundamentals and 3A pattern
- **dependency-injection-testing**: Dependency injection testing strategies
- **test-naming-conventions**: Test naming conventions
- **test-output-logging**: ITestOutputHelper and ILogger integration
- **datetime-testing-timeprovider**: TimeProvider abstraction for time dependencies
- **filesystem-testing-abstractions**: File system dependency abstraction
## Template Files Reference
This skill provides the following template files:
- `templates/mock-patterns.cs`: Complete Mock/Stub/Spy pattern examples
- `templates/verification-examples.cs`: Behavior verification and argument matching examples
- `references/practical-patterns.md`: Five practical patterns with complete code
- `references/test-double-types.md`: Test Double five types detailed examples
## Reference Resources
### Original Articles
This skill content is extracted from "Old School Software Engineer's Testing Practice - 30 Day Challenge" series:
- **Day 07 - Dependency Substitution Entry: Using NSubstitute**
- Ironman Article: https://ithelp.ithome.com.tw/articles/10374593
- Sample Code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day07
### NSubstitute Official
- [NSubstitute Official Website](https://nsubstitute.github.io/)
- [NSubstitute GitHub](https://github.com/nsubstitute/NSubstitute)
- [NSubstitute NuGet](https://www.nuget.org/packages/NSubstitute/)
### Test Double Theory
- [XUnit Test Patterns](http://xunitpatterns.com/Test%20Double.html)
- [Martin Fowler - Test Double](https://martinfowler.com/bliki/TestDouble.html)
1---2name: dotnet-testing-nsubstitute-mocking3description: Using NSubstitute to create test doubles (Mock, Stub, Spy) specialized skill. Used when isolating external dependencies, simulating interface behavior, and validating method calls. Covers Substitute.For, Returns, Received, Throws and complete guidance. Keywords: mock, stub, spy, nsubstitute, mock, test double, test double, IRepository, IService, Substitute.For, Returns, Received, Throws, Arg.Any, Arg.Is, isolate dependencies, simulate external services, dependency injection testing4license: MIT5---67Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.89# NSubstitute Test Double Guide1011## Applicable Scenarios1213This skill focuses on creating and managing test doubles using NSubstitute, covering the five types of Test Doubles,14dependency isolation strategies, behavior setup and validation best practices.1516## Why Do We Need Test Doubles?1718Real-world code usually depends on external resources, which make tests:19201. **Slow** - Need actual database operations, file systems, networks212. **Unstable** - External service failures cause test failures223. **Difficult to Repeat** - Time, random numbers cause inconsistent results234. **Environment Dependent** - Need specific external environment setup245. **Development Blocking** - Must wait for external systems to be ready2526Test doubles allow us to isolate these dependencies and focus on testing business logic.2728## Prerequisites2930### Package Installation3132````xml33<PackageReference Include="NSubstitute" Version="5.3.0" />34<PackageReference Include="xunit" Version="2.9.3" />35<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />36<PackageReference Include="AwesomeAssertions" Version="9.1.0" />37```text3839### Basic using Directives4041```csharp42using NSubstitute;43using NSubstitute.ExceptionExtensions;44using Xunit;45using AwesomeAssertions;46using Microsoft.Extensions.Logging;47```text4849## Test Double Five Types5051According to Gerard Meszaros's definition in "xUnit Test Patterns", test doubles are divided into five types:5253| Type | Purpose | NSubstitute Equivalent |54|------|------|-------------------|55| **Dummy** | Fill objects, only satisfy method signatures | `Substitute.For<T>()` without setting any behavior |56| **Stub** | Provide default return values, set test scenarios | `.Returns(value)` |57| **Fake** | Simplified implementation with real logic | Manual interface implementation (like `FakeUserRepository`) |58| **Spy** | Record calls, verify afterwards | `.Received()` validation |59| **Mock** | Default expected interactions, test fails if not satisfied | `.Received(n)` strict validation |6061> Full code examples for each type please refer to [references/test-double-types.md](references/test-double-types.md)6263## NSubstitute Core Functions6465### Basic Substitution Syntax6667```csharp68// Create interface substitute69var substitute = Substitute.For<IUserRepository>();7071// Create class substitute (needs virtual members)72var classSubstitute = Substitute.For<BaseService>();7374// Create multiple interface substitute75var multiSubstitute = Substitute.For<IService, IDisposable>();76```text7778### Return Value Setup7980#### Basic Return Values8182```csharp83// Exact parameter matching84_repository.GetById(1).Returns(new User { Id = 1, Name = "John" });8586// Any parameter matching87_service.Process(Arg.Any<string>()).Returns("processed");8889// Return sequence values90_generator.GetNext().Returns(1, 2, 3, 4, 5);91```text9293#### Conditional Return Values9495```csharp96// Use delegate to calculate return value97_calculator.Add(Arg.Any<int>(), Arg.Any<int>())98 .Returns(x => (int)x[0] + (int)x[1]);99100// Condition matching101_service.Process(Arg.Is<string>(x => x.StartsWith("test")))102 .Returns("test-result");103```text104105#### Throw Exceptions106107```csharp108// Synchronous method throws exception109_service.RiskyOperation()110 .Throws(new InvalidOperationException("Something went wrong"));111112// Async method throws exception113_service.RiskyOperationAsync()114 .Throws(new InvalidOperationException("Async operation failed"));115```text116117### Argument Matchers118119```csharp120// Any value121_service.Process(Arg.Any<string>()).Returns("result");122123// Specific condition124_service.Process(Arg.Is<string>(x => x.Length > 5)).Returns("long-result");125126// Argument capture127string capturedArg = null;128_service.Process(Arg.Do<string>(x => capturedArg = x)).Returns("result");129_service.Process("test");130capturedArg.Should().Be("test");131132// Argument check133_service.Process(Arg.Is<string>(x =>134{135 x.Should().StartWith("prefix");136 return true;137})).Returns("result");138```text139140### Call Verification141142```csharp143// Verify was called (at least once)144_service.Received().Process("test");145146// Verify call count147_service.Received(2).Process(Arg.Any<string>());148149// Verify was not called150_service.DidNotReceive().Delete(Arg.Any<int>());151152// Verify any argument call153_service.ReceivedWithAnyArgs().Process(default);154155// Verify call order156Received.InOrder(() =>157{158 _service.Start();159 _service.Process();160 _service.Stop();161});162```text163164## Practical Patterns165166Covers five common NSubstitute practical patterns, including complete code examples:167168| Pattern | Description |169|------|------|170| Pattern 1: Dependency Injection and Test Setup | FileBackupService complete example, including constructor injection and SUT setup |171| Pattern 2: Mock vs Stub Differences | Stub focuses on state return values vs Mock focuses on interaction behavior validation |172| Pattern 3: Async Method Testing | `Returns(Task.FromResult(...))` and `.Throws()` patterns |173| Pattern 4: ILogger Validation | Validate underlying `Log` method bypassing extension method limitations |174| Pattern 5: Complex Setup Management | Base test class managing shared Substitute setups |175176> Full code examples please refer to [references/practical-patterns.md](references/practical-patterns.md)177178## Advanced Argument Matching Techniques179180### Complex Object Matching181182```csharp183[Fact]184public void CreateOrder_CreateOrder_ShouldStoreCorrectOrderData()185{186 var repository = Substitute.For<IOrderRepository>();187 var service = new OrderService(repository);188189 service.CreateOrder("Product A", 5, 100);190191 // Verify object properties192 repository.Received(1).Save(Arg.Is<Order>(o =>193 o.ProductName == "Product A" &&194 o.Quantity == 5 &&195 o.Price == 100));196}197```text198199### Argument Capture and Validation200201```csharp202[Fact]203public void RegisterUser_RegisterUser_ShouldGenerateCorrectHashPassword()204{205 var repository = Substitute.For<IUserRepository>();206 var service = new UserService(repository);207208 User capturedUser = null;209 repository.Save(Arg.Do<User>(u => capturedUser = u));210211 service.RegisterUser("john@example.com", "password123");212213 capturedUser.Should().NotBeNull();214 capturedUser.Email.Should().Be("john@example.com");215 capturedUser.PasswordHash.Should().NotBe("password123"); // Should be hashed216 capturedUser.PasswordHash.Length.Should().BeGreaterThan(20);217}218```text219220## Common Pitfalls and Best Practices221222### Recommended Practices2232241. **Target interfaces rather than implementations for Substitutes**225226 ```csharp227 // Correct: target interface228 var repository = Substitute.For<IUserRepository>();229230 // Wrong: target concrete class (unless has virtual members)231 var repository = Substitute.For<UserRepository>();232```text2332342. **Use meaningful test data**235236 ```csharp237 // Correct: clearly express intent238 var user = new User { Id = 123, Name = "John Doe", Email = "john@example.com" };239240 // Wrong: meaningless data241 var user = new User { Id = 1, Name = "test", Email = "a@b.c" };242```text2432443. **Avoid over-verification**245246 ```csharp247 // Correct: only verify important behaviors248 _emailService.Received(1).SendWelcomeEmail(Arg.Any<string>());249250 // Wrong: verify all internal implementation details251 _repository.Received(1).GetById(123);252 _repository.Received(1).Update(Arg.Any<User>());253 _validator.Received(1).Validate(Arg.Any<User>());254```text2552564. **Clear distinction between Mock and Stub**257258 ```csharp259 // Correct: Stub for setting scenarios, Mock for validating behaviors260 var stubRepository = Substitute.For<IUserRepository>(); // Stub261 var mockLogger = Substitute.For<ILogger>(); // Mock262263 stubRepository.GetById(123).Returns(user);264 service.ProcessUser(123);265 mockLogger.Received(1).LogInformation(Arg.Any<string>());266```text267268### Practices to Avoid2692701. **Avoid simulating value types**271272 ```csharp273 // Wrong: DateTime is value type274 var badDate = Substitute.For<DateTime>();275276 // Correct: abstract time provider277 var dateTimeProvider = Substitute.For<IDateTimeProvider>();278 dateTimeProvider.Now.Returns(new DateTime(2024, 1, 1));279```text2802812. **Avoid tight coupling between tests and implementations**282283 ```csharp284 // Wrong: test implementation details285 _repository.Received(1).Query(Arg.Any<string>());286 _repository.Received(1).Filter(Arg.Any<Expression<Func<User, bool>>>());287288 // Correct: test behavior results289 var users = service.GetActiveUsers();290 users.Should().HaveCount(2);291```text2922933. **Avoid overly complex setups**294295 ```csharp296 // Wrong: too many Substitutes (may violate SRP)297 var sub1 = Substitute.For<IService1>();298 var sub2 = Substitute.For<IService2>();299 var sub3 = Substitute.For<IService3>();300 var sub4 = Substitute.For<IService4>();301302 // Correct: reconsider class responsibilities303 // Consider whether violating single responsibility principle, needs refactoring304```text305306## Identifying Dependencies to Substitute307308### Should Substitute309310- External API calls (IHttpClient, IApiClient)311- Database operations (IRepository, IDbContext)312- File system operations (IFileSystem)313- Network communication (IEmailService, IMessageQueue)314- Time dependencies (IDateTimeProvider, TimeProvider)315- Random number generation (IRandom)316- Expensive calculations (IComplexCalculator)317- Logging services (ILogger<T>)318319### Should Not Substitute320321- Value objects (DateTime, string, int)322- Simple data transfer objects (DTO)323- Pure function tools (like AutoMapper's IMapper, consider using real instance)324- Framework core classes (unless explicitly needed)325326## Troubleshooting327328### Q1: How to test classes without interfaces?329330**A:** Ensure members to be simulated are virtual:331332```csharp333public class BaseService334{335 public virtual string GetData() => "real data";336}337338var substitute = Substitute.For<BaseService>();339substitute.GetData().Returns("test data");340```text341342### Q2: How to verify method call order?343344**A:** Use Received.InOrder():345346```csharp347Received.InOrder(() =>348{349 _service.Start();350 _service.Process();351 _service.Stop();352});353```text354355### Q3: How to handle out parameters?356357**A:** Use Returns() with delegate:358359```csharp360_service.TryGetValue("key", out Arg.Any<string>())361 .Returns(x =>362 {363 x[1] = "value";364 return true;365 });366```text367368### Q4: NSubstitute vs Moq which to choose?369370**A:** NSubstitute advantages:371372- More concise and intuitive syntax373- Gentle learning curve374- No privacy controversies375- Sufficient for most testing scenarios376377Choose NSubstitute, unless:378379- Project already uses Moq380- Need Moq-specific advanced features381- Team already familiar with Moq syntax382383## Integration with Other Skills384385This skill can be combined with the following skills:386387- **unit-test-fundamentals**: Unit test fundamentals and 3A pattern388- **dependency-injection-testing**: Dependency injection testing strategies389- **test-naming-conventions**: Test naming conventions390- **test-output-logging**: ITestOutputHelper and ILogger integration391- **datetime-testing-timeprovider**: TimeProvider abstraction for time dependencies392- **filesystem-testing-abstractions**: File system dependency abstraction393394## Template Files Reference395396This skill provides the following template files:397398- `templates/mock-patterns.cs`: Complete Mock/Stub/Spy pattern examples399- `templates/verification-examples.cs`: Behavior verification and argument matching examples400- `references/practical-patterns.md`: Five practical patterns with complete code401- `references/test-double-types.md`: Test Double five types detailed examples402403## Reference Resources404405### Original Articles406407This skill content is extracted from "Old School Software Engineer's Testing Practice - 30 Day Challenge" series:408409- **Day 07 - Dependency Substitution Entry: Using NSubstitute**410 - Ironman Article: https://ithelp.ithome.com.tw/articles/10374593411 - Sample Code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day07412413### NSubstitute Official414415- [NSubstitute Official Website](https://nsubstitute.github.io/)416- [NSubstitute GitHub](https://github.com/nsubstitute/NSubstitute)417- [NSubstitute NuGet](https://www.nuget.org/packages/NSubstitute/)418419### Test Double Theory420421- [XUnit Test Patterns](http://xunitpatterns.com/Test%20Double.html)422- [Martin Fowler - Test Double](https://martinfowler.com/bliki/TestDouble.html)423````