[C# 단위테스트] C# MSTest 단위테스트 하는 방법

참조



소개

  • 안녕하세요. 오늘부터는 틈틈히 시간 나는대로 단위테스트에 대해서 학습하고, 학습한 자료에 대해서 글을 써 공유하려고 합니다.
  • 저는 C#을 주 언어로 사용하고 있어서, 많은 단위테스트 종류 중에서 MSTest 를 이용한 단위테스트를 학습하려고 합니다.
  • 단위테스트의 중요성을 두말할 필요 없을 만큼 매우 중요한데요.
  • 저도 그동안 매일 실무에서 개발을 하면서 시간이 부족하다는 핑계를 이유로 단위테스트 진행 없이 매번 프로그램을 개발해 왔지만..이제라도 단위테스트 습관을 들이고자 열심히 공부해 보려고 합니다.
  • 오늘은 그 첫 번째 시간으로, Visual Studio에서 MSTest를 이용한 단위테스트 하는 방법에 대해서 알려 드리겠습니다.



1. C# 콘솔 프로젝트 생성하기

  • 우선 제일 먼저, Visual Studio를 실행하여 C# 콘솔 프로그램을 하나 생성합니다.
  • 저는 Visual Studio 2019 환경을 사용하였고, .NET5 버전의 콘솔 프로그램을 생성하였습니다.



2. 테스트 할 프로그램 작성하기

  • 단위테스트를 진행하기에 앞서, 테스트 할 대상이 되는 메서드들을 몇개 작성해 보도록 하겠습니다.
  • 저 같은 경우에는 MSDN에서 예제로 사용하고 있는 BankAccount 클래스를 예제 코드로 작성하였습니다.
using System;

namespace UnitTestProgram
{
    /// <summary>
    /// Bank account demo class.
    /// </summary>
    public class BankAccount
    {
        private readonly string m_customerName;
        private double m_balance;

        private BankAccount() { }

        public BankAccount(string customerName, double balance)
        {
            m_customerName = customerName;
            m_balance = balance;
        }

        public string CustomerName
        {
            get { return m_customerName; }
        }

        public double Balance
        {
            get { return m_balance; }
        }

        public void Debit(double amount)
        {
            if (amount > m_balance)
            {
                throw new ArgumentOutOfRangeException("amount");
            }

            if (amount < 0)
            {
                throw new ArgumentOutOfRangeException("amount");
            }

            m_balance -= amount; // intentionally incorrect code
        }

        public void Credit(double amount)
        {
            if (amount < 0)
            {
                throw new ArgumentOutOfRangeException("amount");
            }

            m_balance += amount;
        }

        public void WithDraw(double amount)
        {
            if (m_balance >= amount)
            {
                m_balance -= amount;
            }
            else
            {
                throw new ArgumentException(nameof(amount), "Withdrawal exceeds balance!");
            }
        }

        public static void Main()
        {
            BankAccount ba = new("Mr. Bryan Walton", 11.99);

            ba.Credit(5.77);
            ba.Debit(11.22);

            Console.WriteLine("Current balance is ${0}", ba.Balance);
        }
    }
}



3. MSTest 솔루션 생성하기

  • 앞서 예제코드를 작성하였다면, 이제는 단위테스트 솔루션을 생성합니다.
  • 생성하는 방법은 아래와 같습니다.
  • 솔루션 마우스 우 클릭 -> 추가 -> 새 프로젝트 추가 를 선택합니다.
  • 다음으로 MSTest 프로젝트를 생성하고 이또한 앞서 생성한 Console 프로그램과 같은 프레임워크 버전으로 .NET5 로 생성합니다.
  • 버전이 다르면 단위테스트가 동작하지 않을 수 있어서 반드시 동일한 프레임워크 버전을 사용해서 생성해야 합니다.



4. 테스트 코드 작성

  • 이제는 단위 테스트 진행할 테스트 메서드를 작성합니다.
  • 테스트 진행할 예제 코드는 아래와 같이 작성하였습니다.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UnitTestProgram;

namespace UnitTestProgramTest
{
    [TestClass]
    public class BankAccountTests
    {
        [TestMethod]
        public void Debit_WithValidAmount_UpdatesBalance()
        {
            // Arrange
            double beginningBalance = 11.99;
            double debitAmount = 4.55;
            double expected = 7.44;
            BankAccount account = new("Mr. Bryan Walton", beginningBalance);

            // Act
            account.Debit(debitAmount);

            // Assert
            double actual = account.Balance;
            Assert.AreEqual(expected, actual, 0.001, "Account not debited correctly");
        }

        [TestMethod]
        public void Withdraw_ValidAmount_ChangeBalance()
        {
            // arrange
            double currentBalance = 10.0;
            double withdrawal = 1.0;
            double expected = 9.0;
            BankAccount account = new("JohnDoe", currentBalance);

            // Act
            account.WithDraw(withdrawal);

            // Assert
            Assert.AreEqual(expected, account.Balance);
        }

        [TestMethod]
        public void Withdraw_AmountMoreThanBalance_Throws()
        {
            // arrange
            BankAccount account = new("Jonh Doe", 10.0);

            // act and assert
            Assert.ThrowsException<System.ArgumentException>(() => account.WithDraw(20.0));
        }
    }
}



5. 테스트 진행

  • 이제 단위 테스트 실행을 시켜서 실제로 작성한 테스트 메서드들이 정상적으로 동작하는지 확인합니다.
  • 확인된 결과는 테스트 탐색기 에서 확인할 수 있습니다.
  • 이렇게 테스트 진행 결과, 정상적으로 테스트 통과된 것을 확인할 수 있습니다.



6. 정리

  • 오늘은 간단히 MSTest를 이용해 단위테스트를 진행해 보았습니다.
  • 앞으로 꾸준히 계속 단위테스트에 대해 학습하여 글을 올리도록 하겠습니다.
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY