ภาพรวม
Unit Testing เป็นกระบวนการทดสอบหน่วยโค้ดที่เล็กที่สุด (มักจะเป็นเมธอด) เพื่อให้มั่นใจว่าทำงานถูกต้อง ช่วยลดบั๊ก รองรับการ refactor และเป็นส่วนสำคัญของ Test-Driven Development (TDD)
ขั้นตอนสร้าง Unit Test Project ใน Visual Studio
- เปิด Visual Studio → File → New → Project
- ค้นหา "Unit Test Project" หรือ "xUnit Test Project" (แนะนำ xUnit หรือ NUnit)
- ตั้งชื่อโปรเจกต์ (เช่น MyProject.Tests) → Create
- เพิ่ม 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 |
| MSTest | Built-in ของ Visual Studio เหมาะกับทีมที่ใช้ Microsoft stack เท่านั้น |