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

비밀번호

댓글 작성자
 




... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12402정성태11/7/202011842.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202010860VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207793오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011460.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202010004오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202010187.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208468VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209816오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20208203오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208703오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012805.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202011055디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010801.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010248오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202011033.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202011264Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20209094오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010299오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011204.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208918오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010584VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207973오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202011011.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010417.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011713디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208406오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...