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-mocking-23description: "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 testing"4---5Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.67# NSubstitute Test Double Guide89## Applicable Scenarios1011This skill focuses on creating and managing test doubles using NSubstitute, covering the five types of Test Doubles,12dependency isolation strategies, behavior setup and validation best practices.1314## Why Do We Need Test Doubles?1516Real-world code usually depends on external resources, which make tests:17181. **Slow** - Need actual database operations, file systems, networks192. **Unstable** - External service failures cause test failures203. **Difficult to Repeat** - Time, random numbers cause inconsistent results214. **Environment Dependent** - Need specific external environment setup225. **Development Blocking** - Must wait for external systems to be ready2324Test doubles allow us to isolate these dependencies and focus on testing business logic.2526## Prerequisites2728### Package Installation2930````xml31<PackageReference Include="NSubstitute" Version="5.3.0" />32<PackageReference Include="xunit" Version="2.9.3" />33<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />34<PackageReference Include="AwesomeAssertions" Version="9.1.0" />35```text3637### Basic using Directives3839```csharp40using NSubstitute;41using NSubstitute.ExceptionExtensions;42using Xunit;43using AwesomeAssertions;44using Microsoft.Extensions.Logging;45```text4647## Test Double Five Types4849According to Gerard Meszaros's definition in "xUnit Test Patterns", test doubles are divided into five types:5051| Type | Purpose | NSubstitute Equivalent |52|------|------|-------------------|53| **Dummy** | Fill objects, only satisfy method signatures | `Substitute.For<T>()` without setting any behavior |54| **Stub** | Provide default return values, set test scenarios | `.Returns(value)` |55| **Fake** | Simplified implementation with real logic | Manual interface implementation (like `FakeUserRepository`) |56| **Spy** | Record calls, verify afterwards | `.Received()` validation |57| **Mock** | Default expected interactions, test fails if not satisfied | `.Received(n)` strict validation |5859> Full code examples for each type please refer to [references/test-double-types.md](references/test-double-types.md)6061## NSubstitute Core Functions6263### Basic Substitution Syntax6465```csharp66// Create interface substitute67var substitute = Substitute.For<IUserRepository>();6869// Create class substitute (needs virtual members)70var classSubstitute = Substitute.For<BaseService>();7172// Create multiple interface substitute73var multiSubstitute = Substitute.For<IService, IDisposable>();74```text7576### Return Value Setup7778#### Basic Return Values7980```csharp81// Exact parameter matching82_repository.GetById(1).Returns(new User { Id = 1, Name = "John" });8384// Any parameter matching85_service.Process(Arg.Any<string>()).Returns("processed");8687// Return sequence values88_generator.GetNext().Returns(1, 2, 3, 4, 5);89```text9091#### Conditional Return Values9293```csharp94// Use delegate to calculate return value95_calculator.Add(Arg.Any<int>(), Arg.Any<int>())96 .Returns(x => (int)x[0] + (int)x[1]);9798// Condition matching99_service.Process(Arg.Is<string>(x => x.StartsWith("test")))100 .Returns("test-result");101```text102103#### Throw Exceptions104105```csharp106// Synchronous method throws exception107_service.RiskyOperation()108 .Throws(new InvalidOperationException("Something went wrong"));109110// Async method throws exception111_service.RiskyOperationAsync()112 .Throws(new InvalidOperationException("Async operation failed"));113```text114115### Argument Matchers116117```csharp118// Any value119_service.Process(Arg.Any<string>()).Returns("result");120121// Specific condition122_service.Process(Arg.Is<string>(x => x.Length > 5)).Returns("long-result");123124// Argument capture125string capturedArg = null;126_service.Process(Arg.Do<string>(x => capturedArg = x)).Returns("result");127_service.Process("test");128capturedArg.Should().Be("test");129130// Argument check131_service.Process(Arg.Is<string>(x =>132{133 x.Should().StartWith("prefix");134 return true;135})).Returns("result");136```text137138### Call Verification139140```csharp141// Verify was called (at least once)142_service.Received().Process("test");143144// Verify call count145_service.Received(2).Process(Arg.Any<string>());146147// Verify was not called148_service.DidNotReceive().Delete(Arg.Any<int>());149150// Verify any argument call151_service.ReceivedWithAnyArgs().Process(default);152153// Verify call order154Received.InOrder(() =>155{156 _service.Start();157 _service.Process();158 _service.Stop();159});160```text161162## Practical Patterns163164Covers five common NSubstitute practical patterns, including complete code examples:165166| Pattern | Description |167|------|------|168| Pattern 1: Dependency Injection and Test Setup | FileBackupService complete example, including constructor injection and SUT setup |169| Pattern 2: Mock vs Stub Differences | Stub focuses on state return values vs Mock focuses on interaction behavior validation |170| Pattern 3: Async Method Testing | `Returns(Task.FromResult(...))` and `.Throws()` patterns |171| Pattern 4: ILogger Validation | Validate underlying `Log` method bypassing extension method limitations |172| Pattern 5: Complex Setup Management | Base test class managing shared Substitute setups |173174> Full code examples please refer to [references/practical-patterns.md](references/practical-patterns.md)175176## Advanced Argument Matching Techniques177178### Complex Object Matching179180```csharp181[Fact]182public void CreateOrder_CreateOrder_ShouldStoreCorrectOrderData()183{184 var repository = Substitute.For<IOrderRepository>();185 var service = new OrderService(repository);186187 service.CreateOrder("Product A", 5, 100);188189 // Verify object properties190 repository.Received(1).Save(Arg.Is<Order>(o =>191 o.ProductName == "Product A" &&192 o.Quantity == 5 &&193 o.Price == 100));194}195```text196197### Argument Capture and Validation198199```csharp200[Fact]201public void RegisterUser_RegisterUser_ShouldGenerateCorrectHashPassword()202{203 var repository = Substitute.For<IUserRepository>();204 var service = new UserService(repository);205206 User capturedUser = null;207 repository.Save(Arg.Do<User>(u => capturedUser = u));208209 service.RegisterUser("john@example.com", "password123");210211 capturedUser.Should().NotBeNull();212 capturedUser.Email.Should().Be("john@example.com");213 capturedUser.PasswordHash.Should().NotBe("password123"); // Should be hashed214 capturedUser.PasswordHash.Length.Should().BeGreaterThan(20);215}216```text217218## Common Pitfalls and Best Practices219220### Recommended Practices2212221. **Target interfaces rather than implementations for Substitutes**223224 ```csharp225 // Correct: target interface226 var repository = Substitute.For<IUserRepository>();227228 // Wrong: target concrete class (unless has virtual members)229 var repository = Substitute.For<UserRepository>();230```text2312322. **Use meaningful test data**233234 ```csharp235 // Correct: clearly express intent236 var user = new User { Id = 123, Name = "John Doe", Email = "john@example.com" };237238 // Wrong: meaningless data239 var user = new User { Id = 1, Name = "test", Email = "a@b.c" };240```text2412423. **Avoid over-verification**243244 ```csharp245 // Correct: only verify important behaviors246 _emailService.Received(1).SendWelcomeEmail(Arg.Any<string>());247248 // Wrong: verify all internal implementation details249 _repository.Received(1).GetById(123);250 _repository.Received(1).Update(Arg.Any<User>());251 _validator.Received(1).Validate(Arg.Any<User>());252```text2532544. **Clear distinction between Mock and Stub**255256 ```csharp257 // Correct: Stub for setting scenarios, Mock for validating behaviors258 var stubRepository = Substitute.For<IUserRepository>(); // Stub259 var mockLogger = Substitute.For<ILogger>(); // Mock260261 stubRepository.GetById(123).Returns(user);262 service.ProcessUser(123);263 mockLogger.Received(1).LogInformation(Arg.Any<string>());264```text265266### Practices to Avoid2672681. **Avoid simulating value types**269270 ```csharp271 // Wrong: DateTime is value type272 var badDate = Substitute.For<DateTime>();273274 // Correct: abstract time provider275 var dateTimeProvider = Substitute.For<IDateTimeProvider>();276 dateTimeProvider.Now.Returns(new DateTime(2024, 1, 1));277```text2782792. **Avoid tight coupling between tests and implementations**280281 ```csharp282 // Wrong: test implementation details283 _repository.Received(1).Query(Arg.Any<string>());284 _repository.Received(1).Filter(Arg.Any<Expression<Func<User, bool>>>());285286 // Correct: test behavior results287 var users = service.GetActiveUsers();288 users.Should().HaveCount(2);289```text2902913. **Avoid overly complex setups**292293 ```csharp294 // Wrong: too many Substitutes (may violate SRP)295 var sub1 = Substitute.For<IService1>();296 var sub2 = Substitute.For<IService2>();297 var sub3 = Substitute.For<IService3>();298 var sub4 = Substitute.For<IService4>();299300 // Correct: reconsider class responsibilities301 // Consider whether violating single responsibility principle, needs refactoring302```text303304## Identifying Dependencies to Substitute305306### Should Substitute307308- External API calls (IHttpClient, IApiClient)309- Database operations (IRepository, IDbContext)310- File system operations (IFileSystem)311- Network communication (IEmailService, IMessageQueue)312- Time dependencies (IDateTimeProvider, TimeProvider)313- Random number generation (IRandom)314- Expensive calculations (IComplexCalculator)315- Logging services (ILogger<T>)316317### Should Not Substitute318319- Value objects (DateTime, string, int)320- Simple data transfer objects (DTO)321- Pure function tools (like AutoMapper's IMapper, consider using real instance)322- Framework core classes (unless explicitly needed)323324## Troubleshooting325326### Q1: How to test classes without interfaces?327328**A:** Ensure members to be simulated are virtual:329330```csharp331public class BaseService332{333 public virtual string GetData() => "real data";334}335336var substitute = Substitute.For<BaseService>();337substitute.GetData().Returns("test data");338```text339340### Q2: How to verify method call order?341342**A:** Use Received.InOrder():343344```csharp345Received.InOrder(() =>346{347 _service.Start();348 _service.Process();349 _service.Stop();350});351```text352353### Q3: How to handle out parameters?354355**A:** Use Returns() with delegate:356357```csharp358_service.TryGetValue("key", out Arg.Any<string>())359 .Returns(x =>360 {361 x[1] = "value";362 return true;363 });364```text365366### Q4: NSubstitute vs Moq which to choose?367368**A:** NSubstitute advantages:369370- More concise and intuitive syntax371- Gentle learning curve372- No privacy controversies373- Sufficient for most testing scenarios374375Choose NSubstitute, unless:376377- Project already uses Moq378- Need Moq-specific advanced features379- Team already familiar with Moq syntax380381## Integration with Other Skills382383This skill can be combined with the following skills:384385- **unit-test-fundamentals**: Unit test fundamentals and 3A pattern386- **dependency-injection-testing**: Dependency injection testing strategies387- **test-naming-conventions**: Test naming conventions388- **test-output-logging**: ITestOutputHelper and ILogger integration389- **datetime-testing-timeprovider**: TimeProvider abstraction for time dependencies390- **filesystem-testing-abstractions**: File system dependency abstraction391392## Template Files Reference393394This skill provides the following template files:395396- `templates/mock-patterns.cs`: Complete Mock/Stub/Spy pattern examples397- `templates/verification-examples.cs`: Behavior verification and argument matching examples398- `references/practical-patterns.md`: Five practical patterns with complete code399- `references/test-double-types.md`: Test Double five types detailed examples400401## Reference Resources402403### Original Articles404405This skill content is extracted from "Old School Software Engineer's Testing Practice - 30 Day Challenge" series:406407- **Day 07 - Dependency Substitution Entry: Using NSubstitute**408 - Ironman Article: https://ithelp.ithome.com.tw/articles/10374593409 - Sample Code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day07410411### NSubstitute Official412413- [NSubstitute Official Website](https://nsubstitute.github.io/)414- [NSubstitute GitHub](https://github.com/nsubstitute/NSubstitute)415- [NSubstitute NuGet](https://www.nuget.org/packages/NSubstitute/)416417### Test Double Theory418419- [XUnit Test Patterns](http://xunitpatterns.com/Test%20Double.html)420- [Martin Fowler - Test Double](https://martinfowler.com/bliki/TestDouble.html)421````