bdd-dotnet
# .NET Unit Testing Skill
What this skill does
# .NET Unit Testing Skill
Use this skill when writing unit tests for the Domain.Shared project. This skill captures the unique testing patterns, conventions, and philosophy used in this codebase.
## Testing Philosophy
### Core Principles
- **Ports Testing Only**: Unit tests focus exclusively on testing domain ports (handlers). Each handler represents one user story or use case.
- **Hybrid Testing Approach**: We use real repository implementations with EF Core InMemory database instead of mocks. This "shifts left" to catch issues earlier with more coverage for less effort.
- **No Mock Libraries**: Instead of using mocking frameworks, we create fake implementations for dependencies with realistic behavior.
- **Realistic Behaviors**: Tests cover realistic use cases and behaviors, not artificial scenarios.
- **TDD Support**: The pattern supports Test-Driven Development - start from the test and model, then write ports/handlers and even entity data configurations from tests.
### What to Test
- Handler behavior (command handlers and query handlers)
- Business logic in domain aggregates
- Repository interactions through real implementations
- Workflow and state transitions
- Validation and error handling
- Edge cases and boundary conditions
### What NOT to Test
- Infrastructure implementation details
- Database queries directly
- Third-party library behavior
- Framework features
## Project Structure
### Test Project Configuration
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<!-- NUnit Testing Framework -->
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0"/>
<PackageReference Include="NUnit" Version="3.13.3"/>
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1"/>
<PackageReference Include="NUnit.Analyzers" Version="3.3.0"/>
<!-- InMemory Database for Testing -->
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.32" />
</ItemGroup>
</Project>
```
### Directory Structure
```
RMS.Domain.Tests/
├── Builders/
│ ├── TestContextFactory.cs # Creates test database context
│ ├── TestDataBuilder.cs # Main test data builder with repositories
│ ├── ProductBuilder.cs # Fluent builder for Product aggregate
│ ├── FamilyBuilder.cs # Fluent builder for Family aggregate
│ └── [Other aggregate builders]
├── Fakes/
│ ├── FakeClock.cs # Fake time service
│ ├── FakeUnitOfWork.cs # Fake transaction coordinator
│ ├── FakeBlobStorageService.cs # Fake blob storage
│ └── [Other fake services]
├── Product/
│ ├── SetFamilyToProductCommandHandlerTests.cs
│ └── [Other product handler tests]
├── Competitive/
│ └── [Competitive agreement handler tests]
└── TestData/
└── [CSV files for test data]
```
## Core Testing Components
### 1. TestContextFactory
Creates an EF Core InMemory database context for testing.
```csharp
public class TestContextFactory
{
private readonly DbContextType _contextType;
private readonly string _inMemoryDatabaseName;
public TestContextFactory(
DbContextType contextType = DbContextType.InMemory,
string? inMemoryDatabaseName = null)
{
_contextType = contextType;
_inMemoryDatabaseName = inMemoryDatabaseName ?? Guid.NewGuid().ToString();
}
public MyContext Context => CreateContext(_contextType, _inMemoryDatabaseName);
}
```
**Key Points:**
- Each test gets a unique in-memory database by default
- Can optionally test against LocalSqlServer for integration scenarios
- Database is created automatically via `EnsureCreated()`
### 2. TestDataBuilder
The main orchestrator for test setup. It:
- Creates and holds real repository implementations
- Manages the DbContext lifecycle
- Provides fluent methods to add test data
- Registers services in a ServiceCollection
**Example from SetFamilyToProductCommandHandlerTests.cs:**
```csharp
[SetUp]
public void SetUp()
{
_clock = new FakeClock();
_testDataBuilder = new TestDataBuilder();
_handler = new SetFamilyToProductCommandHandler(
_clock,
_testDataBuilder.ProductRepository, // Real repository!
new NullLogger<SetFamilyToProductCommandHandler>(),
_testDataBuilder.FamilyRepository,
new FakeUnitOfWork());
}
[Test]
public async Task GivenSetProductToFamilyRequest_WhenHandled_ThenFamilyAndProductAreUpdated()
{
// arrange
var Family = new FamilyBuilder().Build();
var productNo = "1234";
var product = new ProductBuilder(productNo, "5678").Build();
_testDataBuilder
.WithFamily(Family)
.WithProduct(product);
var command = new SetFamilyToProductCommand
{
ProductNo = productNo,
FamilyId = Family.Id,
Type = SetFamilyToProductType.SetFamilyCode,
UserId = "userId"
};
// act
var result = await _handler.HandleAsync(command, CancellationToken.None);
// assert
Assert.That(result.Success, Is.True, "Command should be successful");
var updatedProduct = await _testDataBuilder.ProductQueryRepository
.GetAsync(productNo, CancellationToken.None);
Assert.IsNotNull(updatedProduct, "Product should be found");
Assert.That(updatedProduct.FamilyId, Is.EqualTo(Family.Id));
}
```
**TestDataBuilder Key Methods:**
```csharp
// Setup methods (fluent API)
.WithProduct(product)
.WithFamily(Family)
.WithAuthorizedProduct(authorizedProduct)
.WithDistributorSite(distributorSite)
.WithImportProductRequest(request)
.WithCompetitiveAgreement(agreement)
// Retrieval methods
.GetAll<T>() // Get all entities of type T
.CountAll<T>() // Count entities of type T
// Repository access
.ProductRepository
.ProductQueryRepository
.FamilyRepository
.CompetitiveAgreementRepository
// ... many more
```
### 3. Aggregate Builders (Fluent API)
Builders use the fluent pattern to construct domain aggregates with test data.
**ProductBuilder Example:**
```csharp
public class ProductBuilder
{
private readonly string _productNo;
private readonly string? _productClassNo;
private decimal? _listPrice;
private DateTime? _validFrom;
private string? _scaleType;
public ProductBuilder(string productNo, string productClassNo)
{
_productNo = productNo;
_productClassNo = productClassNo;
}
public ProductBuilder WithListPrice(decimal listPrice)
{
_listPrice = listPrice;
return this;
}
public ProductBuilder WithValidFrom(DateTime validFrom)
{
_validFrom = validFrom;
return this;
}
public ProductBuilder WithScaleType(string scaleType)
{
_scaleType = scaleType;
return this;
}
public Product Build()
{
var clock = new FakeClock();
return new Product(
_productNo,
_listPrice,
_validFrom ?? clock.UtcNow(),
_productFamilyNo ?? "fam",
null,
_scaleType ?? "MOTORS",
_productClassNo,
// ... other parameters
);
}
}
// Usage in tests:
var product = new ProductBuilder("12345", "classNo")
.WithListPrice(100.50m)
.WithValidFrom(new DateTime(2024, 1, 1))
.WithScaleType("INDUSTRIAL")
.Build();
```
### 4. Fake Implementations
Create simple, controllable fake implementations instead of using mocking frameworks.
**FakeClock (Control Time):**
```csharp
public class FakeClock : IClock
{
private DateTime _utcNow;
public FakeClock(DateTime? utcNow = null)
{
_utcNow = utcNow ?? DateTime.UtcNow;
}
public DateTime UtcNow() => _utcNow;
public DateTimeOffset ZeroOffsetUtcNow() => _utcNow;
public void OverrideUtcNow(DateTime utcNow)
{
_utcNow = utcNow;
}
}
// Usage:
var clock = new FakeClock(new DateTime(2024, 1, 1)Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.