Comprehensive guide covering:
- What is unit testing and its benefits
- Introduction to XUnit framework
- Why choose XUnit over other frameworks
- XUnit core concepts (Facts, Theories, Fixtures)
- Introduction to Moq mocking framework
- Moq core concepts and advanced features
- Practical examples and best practices
- Advanced testing scenarios
Quick reference for:
- XUnit attributes and assertions
- Moq setup and verification syntax
- Test organization patterns
- Command line test execution
- Best practices summary
- What is unit testing? - Understanding the fundamentals and benefits
- What is XUnit and why should we use it? - Modern testing framework advantages
- How to mock external dependencies using Moq? - Isolation and control in testing
- Async/await testing patterns
- Test data management and builders
- Custom assertions and exceptions
- Test fixtures and collections
- Parameterized testing with Theory
- Test organization and lifecycle management
- Mocking strategies and verification patterns
Core XUnit features and patterns:
MathService.cs- Basic arithmetic operations for testing fundamentalsAsyncMathService.cs- Async operations testing examplesCacheService.cs- Stateful service for fixture demonstrationsCounterService.cs- Shared state testing with class fixturesOrderService.cs- Complex service with multiple dependencies (Moq examples)
SumUnitTests.cs- Basic [Fact] testingDivisionUnitTests.cs- [Theory] with [InlineData] examplesMathUnitTests.cs- Constructor/Dispose lifecycle, custom assertionsCounterUnitTests.cs- Class fixtures, test ordering with prioritiesCacheKeyOneUnitTests.cs&CacheManyKeysUnitTests.cs- Collection fixturesAsyncMathServiceTests.cs- NEW Comprehensive async testing patternsOrderServiceTests.cs- NEW Integration testing with MoqAdvancedXUnitFeaturesTests.cs- NEW Advanced XUnit features showcase
CustomAssert.cs- Custom assertion creationPriorityOrderer.cs- Custom test execution ordering- Test fixtures and collections for shared setup
- Trait-based test categorization
PayloadService.cs- Service layer with database operationsKeyVaultManager.cs- Azure Key Vault integration serviceSQLiteDataAccess.cs- Data access layer- Supporting infrastructure (wrappers, configurations)
PayloadServiceTests.cs- IMPROVED Better structured service testingKeyVaultManagerTests.cs- Basic mocking examplesDataAccessTests.cs- Data layer testing with mocksImprovedKeyVaultManagerTests.cs- NEW Advanced mocking patternsImprovedDataAccessTests.cs- NEW Comprehensive data access testingComprehensiveMoqExamples.cs- NEW Complete Moq feature demonstration
- Basic mock setup and verification
- Argument matching (It.IsAny, It.Is, It.IsInRange, It.IsRegex)
- Return values and dynamic behaviors
- Exception handling and async method mocking
- Callbacks and parameter capture
- Property mocking and verification
- Sequential behavior setup
- Strict mocks and protected method mocking
- Verification patterns and timing constraints
- .NET 6.0 or later
- Visual Studio 2022 / VS Code / JetBrains Rider
# Navigate to a test project
cd UnitTest
# or
cd MoqDemo
# Run all tests
dotnet test
# Run with detailed output
dotnet test --logger "console;verbosity=detailed"
# Run specific test categories
dotnet test --filter "Category=Unit"
dotnet test --filter "Category=Cache"
# Run specific test class
dotnet test --filter "FullyQualifiedName~MathUnitTests"- Open the solution file (
.sln) - Build the solution
- Use Test Explorer to run tests
- Right-click on specific tests to run/debug
- Install the .NET Core Test Explorer extension
- Open the workspace folder
- Use the Test Explorer panel or Command Palette
# Run cache-related tests
dotnet test --filter "Category=Cache"
# Run high-priority tests
dotnet test --filter "Priority=High"
# Run specific test classes
dotnet test --filter "FullyQualifiedName~AsyncMathServiceTests"# Run improved tests
dotnet test --filter "FullyQualifiedName~Improved"
# Run comprehensive examples
dotnet test --filter "FullyQualifiedName~Comprehensive"- Added async/await testing patterns
- Comprehensive Moq usage examples
- Advanced XUnit features demonstration
- Real-world service integration testing
- Test builders for complex object creation
- Improved setup and teardown patterns
- Clear separation of concerns in test classes
- Consistent naming conventions
- Database integration testing with in-memory databases
- External service mocking (Key Vault, Email, Payment processing)
- Error handling and exception testing
- Performance and timeout testing scenarios
- Step-by-step learning progression
- Code samples with detailed explanations
- Best practices and anti-patterns
- Quick reference for daily use
- Start with
UnitTestingGuide.mdfor comprehensive understanding - Explore basic examples in
UnitTest/Tests/SumUnitTests.cs - Progress to parameterized testing in
DivisionUnitTests.cs - Learn test lifecycle in
MathUnitTests.cs - Understand fixtures in cache tests
- Master async testing in
AsyncMathServiceTests.cs - Practice mocking with
MoqDemoexamples - Reference
XUnit-Moq-QuickReference.mdfor syntax help
- Custom test orderers and priority attributes
- Collection definitions and shared fixtures
- Theory data sources (MemberData, ClassData)
- Custom assertions and exception types
- Test output and debugging techniques
- Conditional test execution and skipping
- Argument matchers and custom conditions
- Callback functions and parameter capture
- Sequential behavior and state-based testing
- Protected method mocking
- Strict vs. loose mock behaviors
- Verification strategies and timing
- Arrange-Act-Assert pattern consistency
- Test isolation and independence
- Meaningful test naming conventions
- Appropriate use of test doubles
- Error scenario coverage
- Performance and boundary testing
Feel free to add more examples, improve documentation, or suggest better testing patterns. The goal is to create a comprehensive resource for learning unit testing with XUnit and Moq.
- UnitTest Project: 63 tests passed, 1 skipped β
- MoqDemo Project: 58 tests passed β
- Total Coverage: 121 successful tests
- β Created comprehensive documentation and guides
- β Implemented modern mock-based testing with dependency injection
- β Demonstrated all major XUnit and Moq features
- β Applied best practices for testable code architecture
- β Fixed all compilation and test failures
- β Established patterns for maintainable test suites
- Basic XUnit Features: Facts, Theories, Assertions
- Advanced XUnit: Fixtures, Collections, Custom Assertions, Test Ordering
- Async Testing: Async/await patterns and testing
- Moq Fundamentals: Basic mocking and verification
- Advanced Moq: Callbacks, Sequences, Argument Matching, Protected Methods
- Architecture Patterns: Dependency injection, Interface-based design
- Real-world Scenarios: Service layer testing, Data access mocking, Configuration management
This repository now serves as a comprehensive example of modern .NET unit testing best practices.
This project is for educational purposes. Feel free to use the examples and patterns in your own projects.