xunit
xUnit.net testing framework with Fact, Theory, fixtures, DI, and mocking with Moq and NSubstitute. Covers .NET testing best practices. USE WHEN: user mentions "xUnit", ".NET testing", "Fact", "Theory", "InlineData", "Moq", "NSubstitute", "C# unit test" DO NOT USE FOR: NUnit - use `nunit`, Vitest - use `vitest`, Jest - use `jest`, Playwright - use `playwright`
What this skill does
# xUnit.net - Quick Reference
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `xunit` for comprehensive documentation.
## Basic Tests
```csharp
public class UserServiceTests
{
[Fact]
public async Task GetById_ExistingUser_ReturnsUser()
{
// Arrange
var repository = new Mock<IUserRepository>();
repository.Setup(r => r.GetByIdAsync(1))
.ReturnsAsync(new User { Id = 1, Name = "Alice" });
var service = new UserService(repository.Object, Mock.Of<ILogger<UserService>>());
// Act
var result = await service.GetByIdAsync(1);
// Assert
Assert.NotNull(result);
Assert.Equal("Alice", result.Name);
}
[Fact]
public async Task GetById_NonExistingUser_ReturnsNull()
{
var repository = new Mock<IUserRepository>();
repository.Setup(r => r.GetByIdAsync(999)).ReturnsAsync((User?)null);
var service = new UserService(repository.Object, Mock.Of<ILogger<UserService>>());
var result = await service.GetByIdAsync(999);
Assert.Null(result);
}
}
```
## Theory (Parameterized Tests)
```csharp
[Theory]
[InlineData("", false)]
[InlineData("a", false)]
[InlineData("ab", true)]
[InlineData("[email protected]", true)]
public void Validate_Name_ReturnsExpected(string name, bool expected)
{
var validator = new UserValidator();
var result = validator.IsValidName(name);
Assert.Equal(expected, result);
}
[Theory]
[MemberData(nameof(GetTestUsers))]
public async Task Create_ValidUser_Succeeds(CreateUserRequest request)
{
// Test with complex objects
}
public static IEnumerable<object[]> GetTestUsers()
{
yield return new object[] { new CreateUserRequest("Alice", "[email protected]") };
yield return new object[] { new CreateUserRequest("Bob", "[email protected]") };
}
```
## Mocking with Moq
```csharp
// Setup
var mock = new Mock<IUserRepository>();
// Return value
mock.Setup(r => r.GetByIdAsync(It.IsAny<int>()))
.ReturnsAsync(new User { Id = 1, Name = "Test" });
// Callback
mock.Setup(r => r.AddAsync(It.IsAny<User>()))
.Callback<User>(user => user.Id = 42)
.Returns(Task.CompletedTask);
// Verify
mock.Verify(r => r.AddAsync(It.Is<User>(u => u.Name == "Alice")), Times.Once);
mock.Verify(r => r.DeleteAsync(It.IsAny<int>()), Times.Never);
// Sequence
mock.SetupSequence(r => r.GetByIdAsync(1))
.ReturnsAsync(new User { Name = "First" })
.ReturnsAsync(new User { Name = "Second" });
```
## Mocking with NSubstitute
```csharp
var repository = Substitute.For<IUserRepository>();
// Return value
repository.GetByIdAsync(1).Returns(new User { Id = 1, Name = "Test" });
// Verify
await repository.Received(1).AddAsync(Arg.Is<User>(u => u.Name == "Alice"));
await repository.DidNotReceive().DeleteAsync(Arg.Any<int>());
```
## Fixtures (Shared Context)
```csharp
// Class fixture - shared per test class
public class DatabaseFixture : IAsyncLifetime
{
public AppDbContext Context { get; private set; } = default!;
public async Task InitializeAsync()
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
Context = new AppDbContext(options);
await Context.Database.EnsureCreatedAsync();
}
public async Task DisposeAsync()
{
await Context.DisposeAsync();
}
}
public class UserRepositoryTests : IClassFixture<DatabaseFixture>
{
private readonly AppDbContext _context;
public UserRepositoryTests(DatabaseFixture fixture)
{
_context = fixture.Context;
}
}
// Collection fixture - shared across test classes
[CollectionDefinition("Database")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture> { }
[Collection("Database")]
public class OrderRepositoryTests { }
```
## FluentAssertions (Optional)
```csharp
// Install: dotnet add package FluentAssertions
result.Should().NotBeNull();
result.Name.Should().Be("Alice");
result.Age.Should().BeGreaterThan(0).And.BeLessThan(150);
users.Should().HaveCount(3).And.OnlyContain(u => u.IsActive);
```
## Anti-Patterns
| Anti-Pattern | Why It's Bad | Correct Approach |
|--------------|--------------|------------------|
| Testing implementation details | Brittle tests | Test behavior |
| Shared mutable state | Flaky tests | Use fresh fixtures per test |
| No assertion message | Hard to debug | Use descriptive assertions |
| Testing private methods | Coupling to internals | Test through public API |
## Quick Troubleshooting
| Issue | Likely Cause | Solution |
|-------|--------------|----------|
| Test not discovered | Missing `[Fact]`/`[Theory]` | Add test attribute |
| Fixture not shared | Missing `IClassFixture<T>` | Implement fixture interface |
| Mock returns null | Missing setup | Add `.Setup()` for the call |
| Async test deadlock | Missing `async` keyword | Use `async Task` return type |
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.