Chuyển đến nội dung
Skillpedia
Kiểm thử40k · #7153

csharp-mstest

Skill này làm gì

Hướng dẫn này dạy cách viết kiểm thử code hiệu quả bằng công cụ MSTest. Nó trình bày thực hành tốt nhất để tổ chức code kiểm thử, kiểm tra kết quả và xử lý lỗi.

Khi nào nên dùng

  • ✓Khi bạn tạo kiểm thử để xác minh code có hoạt động đúng không.
  • ✓Khi bạn cần bảo đảm một phần cụ thể của chương trình hoạt động như mong đợi.
  • ✓Khi bạn học cách dùng MSTest để kiểm thử đơn vị.

Liên kết skill

https://github.com/github/awesome-copilot/blob/main/skills/csharp-mstest/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/github/awesome-copilot/blob/main/skills/csharp-mstest/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để kiểm tra xem hàm cộng có trả về giá trị đúng với hai số dương không?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Hướng dẫn tổ chức code kiểm thử thành các class và method, theo một mẫu rõ ràng để viết và kiểm tra kết quả. Nó dùng các lệnh cụ thể để so sánh giá trị, kiểm tra null hoặc xác minh xem có ngoại lệ được ném ra không.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

MSTest Best Practices (MSTest 3.x/4.x)

Your goal is to help me write effective unit tests with modern MSTest, using current APIs and best practices.

Project Setup

  • Use a separate test project with naming convention [ProjectName].Tests
  • Reference MSTest 3.x+ NuGet packages (includes analyzers)
  • Consider using MSTest.Sdk for simplified project setup
  • Run tests with dotnet test

Test Class Structure

  • Use [TestClass] attribute for test classes
  • Seal test classes by default for performance and design clarity
  • Use [TestMethod] for test methods (prefer over [DataTestMethod])
  • Follow Arrange-Act-Assert (AAA) pattern
  • Name tests using pattern MethodName_Scenario_ExpectedBehavior
[TestClass]
public sealed class CalculatorTests
{
    [TestMethod]
    public void Add_TwoPositiveNumbers_ReturnsSum()
    {
        // Arrange
        var calculator = new Calculator();

        // Act
        var result = calculator.Add(2, 3);

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

Test Lifecycle

  • Prefer constructors over [TestInitialize] - enables readonly fields and follows standard C# patterns
  • Use [TestCleanup] for cleanup that must run even if test fails
  • Combine constructor with async [TestInitialize] when async setup is needed
[TestClass]
public sealed class ServiceTests
{
    private readonly MyService _service;  // readonly enabled by constructor

    public ServiceTests()
    {
        _service = new MyService();
    }

    [TestInitialize]
    public async Task InitAsync()
    {
        // Use for async initialization only
        await _service.WarmupAsync();
    }

    [TestCleanup]
    public void Cleanup() => _service.Reset();
}

Execution Order

  1. Assembly Initialization - [AssemblyInitialize] (once per test assembly)
  2. Class Initialization - [ClassInitialize] (once per test class)
  3. Test Initialization (for every test method):
    1. Constructor
    2. Set TestContext property
    3. [TestInitialize]
  4. Test Execution - test method runs
  5. Test Cleanup (for every test method):
    1. [TestCleanup]
    2. DisposeAsync (if implemented)
    3. Dispose (if implemented)
  6. Class Cleanup - [ClassCleanup] (once per test class)
  7. Assembly Cleanup - [AssemblyCleanup] (once per test assembly)

Modern Assertion APIs

MSTest provides three assertion classes: Assert, StringAssert, and CollectionAssert.

Assert Class - Core Assertions

// Equality
Assert.AreEqual(expected, actual);
Assert.AreNotEqual(notExpected, actual);
Assert.AreSame(expectedObject, actualObject);      // Reference equality
Assert.AreNotSame(notExpectedObject, actualObject);

// Null checks
Assert.IsNull(value);
Assert.IsNotNull(value);

// Boolean
Assert.IsTrue(condition);
Assert.IsFalse(condition);

// Fail/Inconclusive
Assert.Fail("Test failed due to...");
Assert.Inconclusive("Test cannot be completed because...");

Exception Testing (Prefer over [ExpectedException])

// Assert.Throws - matches TException or derived types
var ex = Assert.Throws<ArgumentException>(() => Method(null));
Assert.AreEqual("Value cannot be null.", ex.Message);

// Assert.ThrowsExactly - matches exact type only
var ex = Assert.ThrowsExactly<InvalidOperationException>(() => Method());

// Async versions
var ex = await Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetAsync(url));
var ex = await Assert.ThrowsExactlyAsync<InvalidOperationException>(async () => await Method());

Collection Assertions (Assert class)

Assert.Contains(expectedItem, collection);
Assert.DoesNotContain(unexpectedItem, collection);
Assert.ContainsSingle(collection);  // exactly one element
Assert.HasCount(5, collection);
Assert.IsEmpty(collection);
Assert.IsNotEmpty(collection);

String Assertions (Assert class)

Assert.Contains("expected", actualString);
Assert.StartsWith("prefix", actualString);
Assert.EndsWith("suffix", actualString);
Assert.DoesNotStartWith("prefix", actualString);
Assert.DoesNotEndWith("suffix", actualString);
Assert.MatchesRegex(@"\d{3}-\d{4}", phoneNumber);
Assert.DoesNotMatchRegex(@"\d+", textOnly);

Comparison Assertions

Assert.IsGreaterThan(lowerBound, actual);
Assert.IsGreaterThanOrEqualTo(lowerBound, actual);
Assert.IsLessThan(upperBound, actual);
Assert.IsLessThanOrEqualTo(upperBound, actual);

…
Câu hỏi thường gặp

Kiểm thử đơn vị là gì?

Đó là một đoạn code nhỏ kiểm tra xem một phần khác của code (thường là một hàm hoặc method) có hoạt động đúng không.

Tại sao nên dùng một dự án kiểm thử riêng?

Điều này giúp code chính gọn gàng và có tổ chức, vì tách code chạy chương trình khỏi code kiểm tra xem chương trình có đúng không.

Mẫu Arrange-Act-Assert là gì?

Đó là cách viết kiểm thử phổ biến: 1. Arrange: chuẩn bị mọi thứ cần thiết. 2. Act: chạy đoạn code muốn kiểm thử. 3. Assert: kiểm tra xem kết quả có đúng như mong đợi không.

Chi tiết

Mô tả gốc của tác giả

Get best practices for MSTest 3.x/4.x unit testing, including modern assertion APIs and data-driven tests

repo: github/awesome-copilot

Độ phổ biến

Sao GitHub
40k
Vị trí xếp hạng
#7153
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự