🔍

Comprehensive Guide to xUnit Testing

Jun 1, 2025

Xunit Testing in C#

Overview

  • Focus on creating xUnit test projects in C#
  • Writing unit tests using Fact and Theory
  • Utilizing assert methods in unit testing

Setting Up xUnit Test Project

  1. Create xUnit Test Project

    • Use Visual Studio 2022
    • Search and select "xUnit Test Project" with C#
    • Name the project and solution as round-the-code.xunit
    • Choose .NET 8 Long-Term Support
  2. Create Class Library for Testing

    • Right-click solution -> Add new project -> Search "Class Library"
    • Name it round-the-code.xunit-domethods
    • Rename class to NumberHelper
    • Add methods to test:
      • IsOddNumber: Checks if a number is odd using number % 2 == 1
      • IsEvenNumber: Checks if a number is even
      • RatingScore: Uses switch statements to rate scores:
        • Below 3: "bad"
        • 3 to less than 7: "okay"
        • 7 to less than 10: "great"
        • Default: "unknown"

Writing Unit Tests

  1. Adding Test Classes

    • Add dependency of Class Library to Test Project
    • Create a new class NumberHelperFactTests
  2. Writing Fact Tests

    • Example Tests:
      • IsOddNumber: Value 3 should return true
      • IsOddNumber: Value 6 should return false
      • IsEvenNumber: Value 3 should return false
      • IsEvenNumber: Value 6 should return true
    • Use Assert.True or Assert.False
    • Apply [Fact] attribute to each method
  3. Writing Theory Tests

    • Create NumberHelperTheoryTests
    • Copy existing tests and modify:
      • Change [Fact] to [Theory]
      • Use [InlineData] to test multiple inputs
      • Examples:
        • Test odd numbers with inputs like 3, 5, 7
        • Test even numbers with inputs like 2, 4, 6
  4. Testing Rating Scores

    • Use Assert.Equal and Assert.NotEqual
    • Examples:
      • RatingScore: Value 7 should return "great"
      • RatingScore: Value 7 should not return "bad"
    • Apply [Theory] with multiple [InlineData]

Debugging Tests

  • Place breakpoints in tests
  • Right-click -> Debug to stop at breakpoints
  • Inspect parameter values during execution

Conclusion

  • Xunit is crucial for testing code effectively
  • Watch related videos to learn more about xUnit
  • Thorough testing helps prevent bugs in projects