Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 8개 있습니다.)
VS.NET IDE: 105. Visual Studio의 단위 테스트 작성 시 Fakes를 이용한 메서드 재정의 방법
; https://www.sysnet.pe.kr/2/0/10858

VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법
; https://www.sysnet.pe.kr/2/0/12726

.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?)
; https://www.sysnet.pe.kr/2/0/12727

.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
; https://www.sysnet.pe.kr/2/0/12728

.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
; https://www.sysnet.pe.kr/2/0/12729

개발 환경 구성: 590. Visual Studio 2017부터 단위 테스트에 DataRow 특성 지원
; https://www.sysnet.pe.kr/2/0/12749

개발 환경 구성: 593. MSTest - 단위 테스트에 static/instance 유형의 private 멤버 접근 방법
; https://www.sysnet.pe.kr/2/0/12755

.NET Framework: 1084. C# - .NET Core Web API 단위 테스트 방법
; https://www.sysnet.pe.kr/2/0/12756




xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture

지난 글을 봤다면,

MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
; https://www.sysnet.pe.kr/2/0/12728

이제 다른 단위 테스트에서도 문맥이 필요하다는 것을 알 수 있습니다. 단지 제공 방법이 다소 제각각인데요, 일례로 xUnit의 경우에는 Fixture로 문맥 제공을 합니다. 단어가 좀 낯설긴 한데요,

Unit Test에 나오는 Fixture와 Mock은 무엇일까?
; https://zorba91.tistory.com/304

위의 글에서는 "테스트 실행을 위해 베이스라인으로서 사용되는 객체들의 고정된 상태"라고 어찌 보면 원론적인 정의를 하지만 간단하게 "문맥"을 제공하는 걸로 보면 됩니다.

xUnit에서의 문맥 제공 방법은 다음의 글에서 잘 소개하고 있습니다.

Shared Context between Tests
; https://xunit.net/docs/shared-context#class-fixture

천천히 위의 글을 정리해 볼까요? ^^

우선, 메서드 단위의 문맥을 제공하는 방법이 있을 텐데요, MSTest의 경우 이를 위해 TestInitialize/TestCleanup 특성을 적용한 메서드를 만들어 구현을 분리하는 방법도 함께 제공했지만, xUnit의 경우에는 그냥 해당 클래스의 인스턴스를 단위 테스트 메서드마다 생성해서 실행하는 방식만 제공합니다.

일례로 다음의 코드를,

using System;

namespace ClassLibrary1
{
    public class Class1 : IDisposable
    {
        public int Add(int x, int y)
        {
            return x + y;
        }

        public int Subtract(int x, int y)
        {
            return x - y;
        }

        public void Dispose()
        {
            System.Diagnostics.Trace.WriteLine("Disposed");
        }
    }
}

테스트하는 xUnit은 이렇게 구성할 텐데요,

namespace ClassLibrary1.Tests
{
    public class Class1Tests
    {
        [Fact()]
        public void AddTest()
        {
            Class1 cl = new Class1();
            Assert.Equal(4, cl.Add(1, 3));
        }

        [Fact()]
        public void SubtractTest()
        {
            Class1 cl = new Class1();
            Assert.Equal(-2, cl.Subtract(1, 3));
        }
    }
}

여기서 반복이 되는 "Class1 cl = new Class1();" 코드를 단순히 단위 테스트 클래스의 생성자와 IDisposable을 이용해 다음과 같이 대체하기만 하면 됩니다.

namespace ClassLibrary1.Tests
{
    public class Class1Tests : IDisposable
    {
        Class1 _cl = new Class1();

        public void Dispose()
        {
            _cl.Dispose();
        }

        [Fact()]
        public void AddTest()
        {
            Assert.Equal(4, _cl.Add(1, 3));
        }

        [Fact()]
        public void SubtractTest()
        {
            Assert.Equal(-2, _cl.Subtract(1, 3));
        }
    }
}




반면, 클래스 단위의 초기화는 xUnit도 더 이상 방법이 없습니다. 별도로 부가적인 해법을 내놓아야 하는데, 이때 사용하는 방법이 바로 IClassFixture입니다.

이를 위해 문맥으로 유지될 클래스를 하나 별도로 정의하고, 그 내부에 문맥 상태 정보를 담을 인스턴스 필드를 추가합니다.

public class DatabaseFixture : IDisposable
{
    SqlConnection _db;

    public DatabaseFixture()
    {
        _db = new SqlConnection();
    }

    public void Run(string cmd)
    {
        /* code */
    }

    public void Dispose()
    {
        _db.Dispose();
    }
}

그다음 단위 테스트 코드 측에서는,

public class Class1Tests : IDisposable, IClassFixture<DatabaseFixture>
{
    Class1 _cl = new Class1();
    DatabaseFixture _dbFixture; // 외부에서 단 한 번만 생성해 테스트 클래스의 인스턴스마다 전달

    public Class1Tests(DatabaseFixture fixture)
    {
        _dbFixture = fixture;
    }

    public void Dispose()
    {
        _cl.Dispose();
    }

    [Fact()]
    public void AddTest()
    {
        Assert.Equal(4, _cl.Add(1, 3));
        _dbFixture.Run("...");
    }

    [Fact()]
    public void SubtractTest()
    {
        Assert.Equal(-2, _cl.Subtract(1, 3));
        _dbFixture.Run("...");
    }
}

보는 바와 같이, 해당 개체를 형식 매개 변수로 전달받는 IClassFixture를 상속받고 생성자를 통해 Injection을 받는 방식으로 그 인스턴스를 단일하게 유지하며 사용할 수 있습니다.




특이하게, xUnit은 여러 개의 클래스에서도 단 하나의 문맥을 공유할 수 있는 방법을 제공하는데 이때 사용하는 인터페이스가 바로 ICollectionFixture입니다.

방법은, 테스트 런타임 시에 문맥 상태 정보를 담고 있는 클래스와 그것의 유일한 인스턴스를 소유할 dummy 클래스를 함께 만들어 두고,

// 전역적으로 공유될 상태 정보를 갖는 클래스 정의
public class GlobalFixture : IDisposable
{
    static HttpClientHandler _sharedHandler = new HttpClientHandler();

    public async Task HttpCall(string url)
    {
        using (HttpMessageInvoker httpClient = new HttpMessageInvoker(_sharedHandler, false))
        {
            try
            {
                HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, url);
                HttpResponseMessage resp = await httpClient.SendAsync(req, CancellationToken.None);
                string result = await resp.Content.ReadAsStringAsync();
            }
            catch { }
        }
    }

    public void Dispose()
    {
        _sharedHandler.Dispose();
    }
}

// 더미 클래스 생성
[CollectionDefinition("Global.Status")] // CollectionDefinition 특성에는 식별자 전달
public class GlobalStateCollection : ICollectionFixture<GlobalFixture>
{
    // This class has no code, and is never created. Its purpose is simply
    // to be the place to apply [CollectionDefinition] and all the
    // ICollectionFixture<> interfaces.
}

해당 개체를 공유할 테스트 클래스 측에서 저 ICollectionFixture를 사용하겠다는 명시를 Collection 특성으로 정의하고 생성자를 통해 전달받으면 됩니다.

[Collection("Global.Status")]
public class Class1Tests : IDisposable, IClassFixture<DatabaseFixture>
{
    DatabaseFixture _dbFixture;
    GlobalFixture _globalFixture;

    public Class1Tests(DatabaseFixture fixture, GlobalFixture globalFixture)
    {
        _dbFixture = fixture;
        _globalFixture = globalFixture;
    }

    // ...[생략]...
}

위의 경우와 같이 다른 테스트 클래스에서도 동일한 GlobalFixture 인스턴스를 전달받겠다고 다음과 같이 추가할 수 있습니다.

[Collection("Global.Status")]
public class AnotherTests : IDisposable
{
    GlobalFixture _globalFixture;

    public Class1Tests(GlobalFixture globalFixture)
    {
        _globalFixture = globalFixture;
    }

    // ...[생략]...
}

어찌 보면, MSTest에서는 저런 문맥 정보를 AssemblyInitialize/AssemblyCleanup에서 했다고 봐도 무방할 것입니다.




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







[최초 등록일: ]
[최종 수정일: 7/22/2021]

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)
13628정성태5/17/2024203개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/2024198오류 유형: 903. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/2024253Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/2024586닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/2024794Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/2024912닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/2024978닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/2024896오류 유형: 902. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/20241025VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/2024986닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20241104닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20241050닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/2024991닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/2024948닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/2024875닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/2024910닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/2024930오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/2024938닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/20241007닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/20241047닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/20241117닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/20241125닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/20241079닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/20241107닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/20241066오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...