Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법

예전에 .NET Framework 환경에서만 하다가,

Visual Studio의 단위 테스트 작성 시 Fakes를 이용한 메서드 재정의 방법
; https://www.sysnet.pe.kr/2/0/10858

.NET core/5+ 환경으로 오면서는 해본 적이 없어 이참에 한번 해봤습니다.




우선, .NET 6 라이브러리 프로젝트를 만들고, 테스트를 위해 Microsoft.Data.SqlClient 패키지를 참조한 다음,

Install-Package Microsoft.Data.SqlClient

이렇게 코드를 추가합니다.

using Microsoft.Data.SqlClient;

namespace ClassLibrary1
{
    public class Class1
    {
        public void Test()
        {
            SqlConnection sqlCon = new SqlConnection();
            sqlCon.ConnectionString = "test";
            sqlCon.Open();
        }
    }
}

당연히 위의 코드는 연결 문자열이 잘못되었으므로 그냥 실행하면 예외가 발생합니다. 자, 그럼 이 상태에서 Test 메서드를 우클릭해 단위 테스트를 만들고,

net6_fake_1.png

이로 인해 생성한 ClassLibrary1Tests 프로젝트의 "Dependencies" 하위에서 Microsoft.Data.SqlClient.dll에 대해 "Add Fakes Assembly" 메뉴를 선택합니다.

net6_fake_2.png

그럼 다음과 같이 "Fakes" 디렉터리가 생기고 "Microsoft.Data.SqlClient.fakes" 항목이 생깁니다.

net6_fake_3.png

Microsoft.Data.SqlClient.fakes 파일을 열어보면 단순 텍스트 파일이고 여기서 좀 더 상세한 제어를 추가할 수 있습니다.

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="Microsoft.Data.SqlClient" Version="5.0.0.0"/>
</Fakes>

환경 설정은 이걸로 끝입니다, 남은 작업은 Shim을 이용해 테스트를 작성하기만 하면 됩니다.

using Microsoft.Data.SqlClient.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ClassLibrary1.Tests
{
    [TestClass()]
    public class Class1Tests
    {
        [TestMethod()]
        public void TestTest()
        {
            using (ShimsContext.Create())
            {
                ShimSqlConnection.AllInstances.Open =
                    (thisInstance) => Console.WriteLine("Open");

                Class1 class1 = new Class1();
                class1.Test();
            }
        }
    }
}

원래 코드에서는 ConnectionString에 "test" 연결 문자열을 줬기 때문에 예외가 발생해야 하지만, 위의 ShimsContext 내에서 실행하는 SqlConnection.Open은 Console.WriteLine 코드만 수행하므로 아무런 예외 없이 테스트 통과를 하게 됩니다.

net6_fake_4.png

.NET Framework 시절과 비교해 딱히 바뀐 것은 없고, 단지 Fake 해야 할 어셈블리를 찾기 위해 Dependencies를 헤매야 하는 불편함 정도만 있습니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/15/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13854정성태12/27/20245851C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20244793디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20245887디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20245094디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20246205오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20246182디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20245679디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20245754오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20246299디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20245156디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20246654디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20245182오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20245367디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/20245979오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20245261오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/20246179오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/20245939오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/20246738디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20245285디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/20246710오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/20246696Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
13833정성태11/29/20246061개발 환경 구성: 737. Azure Web App에서 Scale-out으로 늘어난 리눅스 인스턴스에 SSH 접속하는 방법
13832정성태11/27/20245694Windows: 274. Windows 7부터 도입한 conhost.exe
13831정성태11/27/20245055Linux: 111. eBPF - BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_RINGBUF에 대한 다양한 용어들
13830정성태11/25/20246562개발 환경 구성: 736. 파이썬 웹 앱을 Azure App Service에 배포하기
13829정성태11/25/20246665스크립트: 67. 파이썬 - Windows 버전에서 함께 설치되는 py.exe
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...