본문으로 건너뛰기
Skillpedia
테스트40k · #7153

csharp-mstest

하는 일

이 안내서는 MSTest 도구를 사용해 효율적인 코드 테스트를 작성하는 방법을 가르칩니다. 테스트 코드를 정리하고, 결과를 확인하고, 오류를 처리하는 모범 사례를 보여 줍니다.

사용하는 경우

  • ✓코드가 올바르게 작동하는지 확인하는 테스트를 만들 때.
  • ✓프로그램의 특정 부분이 기대대로 작동하는지 확인해야 할 때.
  • ✓단위 테스트를 위해 MSTest 도구를 배울 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/github/awesome-copilot/blob/main/skills/csharp-mstest/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“두 개의 양수를 더했을 때 덧셈 함수가 올바른 값을 반환하는지 어떻게 테스트할 수 있나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

안내서는 테스트 코드를 클래스와 메서드로 정리하고, 결과를 작성하고 확인하는 명확한 패턴을 따릅니다. 값을 비교하거나, null을 확인하거나, 예외가 발생했는지 확인하는 특정 명령을 사용합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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);

…
자주 묻는 질문

단위 테스트란 무엇인가요?

다른 코드 부분(보통 함수나 메서드)이 제대로 작동하는지 확인하는 작은 코드입니다.

테스트 프로젝트를 따로 두는 이유는 무엇인가요?

프로그램을 실행하는 코드와 올바르게 작동하는지 확인하는 코드를 분리해서, 주 코드를 깔끔하고 체계적으로 유지하도록 돕습니다.

Arrange-Act-Assert 패턴이란 무엇인가요?

테스트를 구성하는 흔한 방법입니다. 1. Arrange(준비): 필요한 모든 것을 설정합니다. 2. Act(실행): 테스트할 코드를 실행합니다. 3. Assert(검증): 결과가 기대한 것인지 확인합니다.

상세 정보

작성자의 원본 설명

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

repo: github/awesome-copilot

인기도

GitHub 스타
40k
순위
#7153
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬