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

비밀번호

댓글 작성자
 




... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11374정성태11/27/201728335사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201727564오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201729546사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201723281오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201723952오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201725302사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201730098.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201731102개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201723291오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201723675오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201727710사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201727936사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201722456오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201725480오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201726688오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201725484오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201731288사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
11357정성태11/15/201731632개발 환경 구성: 336. 윈도우 10 Bash 쉘에서 C++ 컴파일하는 방법
11356정성태11/15/201733399사물인터넷: 8. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 [4]
11355정성태11/15/201727293사물인터넷: 7. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 [2]파일 다운로드2
11354정성태11/14/201733154사물인터넷: 6. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드로 쓰는 방법 [8]
11353정성태11/14/201729645사물인터넷: 5. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 이더넷 카드로 쓰는 방법 [1]
11352정성태11/14/201726530사물인터넷: 4. Samba를 이용해 윈도우와 Raspberry Pi간의 파일 교환 [1]
11351정성태11/7/201728637.NET Framework: 698. C# 컴파일러 대신 직접 구현하는 비동기(async/await) 코드 [6]파일 다운로드1
11350정성태11/1/201725147디버깅 기술: 108. windbg 분석 사례 - Redis 서버로의 호출을 기다리면서 hang 현상 발생
11349정성태10/31/201725963디버깅 기술: 107. windbg - x64 SOS 확장의 !clrstack 명령어가 출력하는 Child SP 값의 의미 [1]파일 다운로드1
... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...