tdd-workflow
Test-Driven Development workflow for .NET. Use when implementing features, fixing bugs, or writing new code. Guides RED-GREEN-REFACTOR cycle with proper test design.
What this skill does
# Test-Driven Development Workflow
## The TDD Cycle: RED-GREEN-REFACTOR
```
┌─────────────────────────────────────┐
│ │
│ ┌─────┐ ┌───────┐ ┌─────┐ │
│ │ RED │───▶│ GREEN │───▶│REFAC│──┘
│ └─────┘ └───────┘ └─────┘
│ │ │
│ │ Write failing test │
│ │ │
│ ▼ │
│ Make it pass (minimal) │
│ │
└──────────────────────────────┘
Improve design
```
## Phase 1: RED - Write a Failing Test
### Rules for RED Phase
1. Write ONE test that fails
2. Test must fail for the RIGHT reason
3. Test must be meaningful and specific
4. Run the test to confirm it fails
### Test Naming Convention
```
{MethodUnderTest}_{Scenario}_{ExpectedBehavior}
```
**Examples:**
- `CreateOrder_WithValidItems_ReturnsOrder`
- `GetUser_WhenNotFound_ThrowsNotFoundException`
- `CalculateTotal_WithDiscount_AppliesCorrectPercentage`
### AAA Pattern (Arrange-Act-Assert)
```csharp
[Fact]
public void MethodName_Scenario_ExpectedResult()
{
// Arrange - Set up preconditions
var sut = new SystemUnderTest();
var input = CreateValidInput();
// Act - Execute the behavior
var result = sut.Execute(input);
// Assert - Verify outcome
Assert.Equal(expected, result);
}
```
### Test Categories
```csharp
// Unit Test - Tests single unit in isolation
[Fact]
public void Calculator_Add_ReturnsSumOfNumbers() { }
// Integration Test - Tests component interaction
[Fact]
public void OrderService_CreateOrder_PersistsToDatabase() { }
// Acceptance Test - Tests user scenarios
[Fact]
public void User_CanCompleteCheckout_WithValidCart() { }
```
## Phase 2: GREEN - Make It Pass
### Rules for GREEN Phase
1. Write MINIMAL code to pass the test
2. Do NOT add extra features
3. Do NOT optimize yet
4. It's okay to be "ugly" - we'll fix it in REFACTOR
5. Run tests to confirm they pass
### The Simplest Thing That Works
```csharp
// BAD - Over-engineering in GREEN phase
public decimal CalculateDiscount(Order order)
{
var strategy = _discountStrategyFactory.Create(order.CustomerType);
return strategy.Calculate(order, _configService.GetDiscountRules());
}
// GOOD - Minimal implementation for GREEN
public decimal CalculateDiscount(Order order)
{
return order.Total * 0.1m; // 10% discount
}
```
### Fake It Till You Make It
```csharp
// Test expects specific value
[Fact]
public void GetGreeting_ReturnsHello()
{
var result = greeter.GetGreeting();
Assert.Equal("Hello", result);
}
// GREEN: Just return what the test expects
public string GetGreeting() => "Hello";
```
## Phase 3: REFACTOR - Improve Design
### Rules for REFACTOR Phase
1. Tests MUST stay green
2. Improve structure, not behavior
3. Apply SOLID principles
4. Remove duplication (DRY)
5. Simplify (KISS)
6. Remove unused code (YAGNI)
### Refactoring Checklist
- [ ] Extract methods for clarity
- [ ] Rename for intent
- [ ] Remove duplication
- [ ] Apply design patterns if needed
- [ ] Check for SOLID violations
- [ ] Run tests after each change
### Common Refactorings
```csharp
// Before: Long method
public void ProcessOrder(Order order)
{
// 50 lines of mixed concerns
}
// After: Single responsibility
public void ProcessOrder(Order order)
{
ValidateOrder(order);
CalculateTotals(order);
ApplyDiscounts(order);
PersistOrder(order);
NotifyCustomer(order);
}
```
## Test Doubles
### Types of Test Doubles
```csharp
// Dummy - Passed but never used
var dummyLogger = new Mock<ILogger>().Object;
// Stub - Provides canned answers
var stubRepo = new Mock<IUserRepository>();
stubRepo.Setup(r => r.GetById(1)).Returns(new User { Id = 1 });
// Spy - Records interactions
var spyNotifier = new SpyNotifier();
service.Execute();
Assert.True(spyNotifier.WasCalled);
// Mock - Verifies interactions
var mockNotifier = new Mock<INotifier>();
service.Execute();
mockNotifier.Verify(n => n.Send(It.IsAny<Message>()), Times.Once);
// Fake - Working implementation (in-memory)
var fakeRepo = new InMemoryUserRepository();
```
### When to Use What
| Double | Use When |
|--------|----------|
| Dummy | Parameter required but unused |
| Stub | Need controlled return values |
| Spy | Need to verify calls were made |
| Mock | Need to verify specific interactions |
| Fake | Need realistic behavior without dependencies |
## Test Organization
### Project Structure
```
src/
├── MyApp.Domain/
│ └── Entities/
├── MyApp.Application/
│ └── Services/
└── MyApp.Infrastructure/
└── Repositories/
tests/
├── MyApp.Domain.Tests/
│ └── Entities/
├── MyApp.Application.Tests/
│ └── Services/
└── MyApp.Integration.Tests/
└── Repositories/
```
### Test Class Structure
```csharp
public class OrderServiceTests
{
private readonly Mock<IOrderRepository> _mockRepository;
private readonly Mock<INotificationService> _mockNotifier;
private readonly OrderService _sut;
public OrderServiceTests()
{
_mockRepository = new Mock<IOrderRepository>();
_mockNotifier = new Mock<INotificationService>();
_sut = new OrderService(_mockRepository.Object, _mockNotifier.Object);
}
[Fact]
public void CreateOrder_WithValidData_PersistsOrder() { }
[Fact]
public void CreateOrder_WithInvalidData_ThrowsValidationException() { }
}
```
## Anti-Patterns to Avoid
### Test Smells
```csharp
// BAD: Testing implementation details
Assert.Equal(3, order.Items.Count);
// GOOD: Testing behavior
Assert.True(order.HasItems);
// BAD: Multiple assertions testing different behaviors
[Fact]
public void Order_Tests()
{
Assert.NotNull(order.Id);
Assert.Equal("Pending", order.Status);
Assert.True(order.Total > 0);
}
// GOOD: One logical assertion per test
[Fact]
public void NewOrder_HasPendingStatus()
{
Assert.Equal(OrderStatus.Pending, order.Status);
}
// BAD: Tests depending on order
[Fact]
public void Test1_CreateUser() { } // Creates user
[Fact]
public void Test2_GetUser() { } // Assumes user exists
// GOOD: Independent tests
[Fact]
public void GetUser_WhenExists_ReturnsUser()
{
var user = CreateUser(); // Arrange includes setup
var result = _sut.GetUser(user.Id);
Assert.NotNull(result);
}
```
## Quick Reference
### TDD Commands
```bash
# Run all tests
dotnet test
# Run with coverage
dotnet test /p:CollectCoverage=true
# Run specific test
dotnet test --filter "FullyQualifiedName~OrderServiceTests"
# Watch mode
dotnet watch test
```
### Test Attributes
```csharp
[Fact] // Single test case
[Theory] // Parameterized test
[InlineData(1, 2)] // Test data
[Trait("Category", "Unit")] // Categorization
[Skip("Reason")] // Skip test
```
See [patterns.md](patterns.md) for advanced testing patterns.
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.