Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การทดสอบหน่วย (Unit Testing) สำหรับโค้ด C#

ภาพรวม

Unit Testing เป็นกระบวนการทดสอบหน่วยโค้ดที่เล็กที่สุด (มักจะเป็นเมธอด) เพื่อให้มั่นใจว่าทำงานถูกต้อง ช่วยลดบั๊ก รองรับการ refactor และเป็นส่วนสำคัญของ Test-Driven Development (TDD)

ขั้นตอนสร้าง Unit Test Project ใน Visual Studio

  1. เปิด Visual Studio → File → New → Project
  2. ค้นหา "Unit Test Project" หรือ "xUnit Test Project" (แนะนำ xUnit หรือ NUnit)
  3. ตั้งชื่อโปรเจกต์ (เช่น MyProject.Tests) → Create
  4. เพิ่ม Reference ไปยังโปรเจกต์ที่ต้องการทดสอบ (Right-click Dependencies → Add Project Reference)

ตัวอย่าง Unit Test ด้วย xUnit (แนะนำสมัยใหม่)


using Xunit;
using MyProject; // โปรเจกต์ที่ต้องการทดสอบ

public class CalculatorTests {
    [Fact]
    public void Add_TwoNumbers_ReturnsSum() {
        // Arrange
        var calc = new Calculator();

        // Act
        int result = calc.Add(2, 3);

        // Assert
        Assert.Equal(5, result);
    }

    [Theory]
    [InlineData(1, 2, 3)]
    [InlineData(-1, 1, 0)]
    [InlineData(0, 0, 0)]
    public void Add_MultipleCases_ReturnsCorrectSum(int a, int b, int expected) {
        var calc = new Calculator();
        int result = calc.Add(a, b);
        Assert.Equal(expected, result);
    }
}

หลักการสำคัญ

  • AAA Pattern: Arrange (เตรียมข้อมูล) → Act (เรียกเมธอด) → Assert (ตรวจสอบผลลัพธ์)
  • TDD: เขียน Test ก่อน → รัน Test ให้ล้มเหลว (Red) → เขียนโค้ดให้ผ่าน (Green) → Refactor
  • Test ควรเป็น Fast, Independent, Repeatable, Self-validating, Timely (FIRST principles)
  • หลีกเลี่ยงการทดสอบ implementation details ให้ทดสอบ behavior แทน

Framework ยอดนิยม

Frameworkคุณสมบัติ
xUnitสมัยใหม่ ยืดหยุ่น ไม่มี static state รองรับ parallel testing
NUnitเก่า มATURE ฟีเจอร์มาก รองรับ TestCase Attribute
MSTestBuilt-in ของ Visual Studio เหมาะกับทีมที่ใช้ Microsoft stack เท่านั้น