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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12740정성태7/29/20217383오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/20217361오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/20217969오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/20216921오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/20217473오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/20217985.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202123950스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202111218.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/20216530오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/20217726개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/20219251개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/20218216.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/20217666.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/20218679.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/20218496VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/20217195오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/20219917개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/20217547오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/20217359오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/20217960오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/20217335Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/20216509오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/20217093개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/20217044Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
12716정성태7/17/20217868개발 환경 구성: 580. msbuild의 Exec Task에 robocopy를 사용하는 방법파일 다운로드1
12715정성태7/17/20219503오류 유형: 736. Windows - MySQL zip 파일 버전의 "mysqld --skip-grant-tables" 실행 시 비정상 종료 [1]
... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...