Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 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




MSTest - 단위 테스트에 static/instance 유형의 private 멤버 접근 방법

예를 들어, 다음과 같은 식의 코드가 있다고 가정할 때,

using System;
using System.Diagnostics;

namespace ClassLibrary1
{
    public class Class1
    {
        int _waitTime = 5000;
        Stopwatch _st;

        public void Start()
        {
            _st = new Stopwatch();
            _st.Start();
        }

        public bool IsTooSlow()
        {
            long elapsed = _st.ElapsedMilliseconds;
            if (elapsed > _waitTime)
            {
                return true;
            }

            return false;
        }
    }
}

단위 테스트를 이런 식으로 작성하게 될 텐데요,

using ClassLibrary1;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;

namespace ClassLibrary1.Tests
{
    [TestClass()]
    public class Class1Tests
    {
        Class1 _cl = new Class1();

        [TestMethod()]
        [DataRow(false, 3000)]
        [DataRow(true, 5016)]
        public void IsTooSlowTest(bool expected, int sleepTime)
        {
            _cl.Start();
            Thread.Sleep(sleepTime);
            Assert.AreEqual(expected, _cl.IsTooSlow());
        }
    }
}

그런데, 매번 저걸 테스트할 때마다 8초씩 기다려야 하는 걸까요? 물론, Class1의 _waitTime이 꼭 5000이어야 한다면 할 수 없지만, 단위 테스트에 한해 저 값을 바꿔도 무방한 코드라면 유연함을 발휘하는 것이 좋습니다.

이런 경우 선택할 수 있는 방법이 해당 필드를 internal 접근 유형으로 바꾸고, InternalsVisibleTo를 이용해 단위 테스트 프로젝트를 등록하면 됩니다.

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("ClassLibrary1Tests")]

namespace ClassLibrary1
{
    public class Class1
    {
        internal int _waitTime = 5000;
        
        // ...[생략]...
    }
}

그럼 단위 테스트 프로젝트에서 이렇게 internal 필드를 접근할 수 있어,

[TestMethod()]
[DataRow(false, 16)]
[DataRow(true, 46)]
public void IsTooSlowTest(bool expected, int sleepTime)
{
    _cl._waitTime = 30;

    _cl.Start();
    Thread.Sleep(sleepTime);
    Assert.AreEqual(expected, _cl.IsTooSlow());
}

단위 테스트 시간을 절약할 수 있습니다.




하지만, 경우에 따라서는 매번 private 필드를 internal로 바꾸는 것이 타당하지 않을 수 있습니다. 그렇다고 단위 테스트를 위해 SetWaitTime internal 메서드를 두는 것도 부담스럽다면, 마지막으로 적용할 수 있는 방법이 바로 private 필드를 Reflection으로 접근해 보는 것입니다.

사실, .NET Framework 환경에서는 마이크로소프트가 이런 경우를 위해 PrivateObject/PrivateType을 제공하고 있었습니다. 그래서 위의 예제라면 다음과 같은 식으로 사용할 수 있습니다.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;

namespace ClassLibrary1.Tests
{
    [TestClass()]
    public class Class1Tests
    {
        Class1 _cl;        
        PrivateObject _prvObj; // instance private 접근
        PrivateType _prvType; // static private 접근

        [TestInitialize]
        public void TestInitialize()
        {
            _cl = new Class1();
            _prvObj = new PrivateObject(_cl);
            _prvType = new PrivateType(typeof(Class1));
        }

        [TestMethod()]
        [DataRow(false, 16)]
        [DataRow(true, 46)]
        public void IsTooSlowTest(bool expected, int sleepTime)
        {
            _prvObj.SetField("_waitTime", 30);

            // 만약 정적 필드라면,
            // _prvType.SetStaticField("_waitTime", 30);

            _cl.Start();
            Thread.Sleep(sleepTime);
            Assert.AreEqual(expected, _cl.IsTooSlow());
        }
    }
}

아쉽게도 PrivateObject/PrivateType은 .NET Core/5+ 환경의 단위 테스트 프로젝트에서는 더 이상 제공하지 않고 있습니다.

PrivateObject and PrivateType are not available for a project targeting netcorapp2.0 #366
; https://github.com/Microsoft/testfx/issues/366

어쩔 수 없습니다. 직접 만들든가 해야 하는데, 그래도 위의 덧글을 보면 마이크로소프트 측의 구현 코드 위치와 함께,

testfx/src/TestFramework/Extension.Desktop/
; https://github.com/microsoft/testfx/tree/664ac7c2ac9dbfbee9d2a0ef560cfd72449dfe34/src/TestFramework/Extension.Desktop

아예 zip 파일로 제공해 주고 있습니다. ^^ (첨부 파일의 프로젝트에도 PrivateObjectPrivateType.cs 파일을 포함하고 있습니다.)

PrivateObjectPrivateType.zip
; https://github.com/microsoft/testfx/files/4132970/PrivateObjectPrivateType.zip

따라서, PrivateObjectPrivateType.cs을 그대로 .NET Core/5+ 단위 테스트 프로젝트에 복사해 주고 이전 PrivateObject/PrivateType 사용 코드를 그대로 활용할 수 있습니다.

참고로, 다음의 편의성 메서드도 있으니 참고하시고.

[PrivateObject]
    GetArrayElement
    GetField
    GetFieldOrProperty
    GetProperty
    Invoke
    SetArrayElement
    SetField
    SetFieldOrProperty
    SetProperty

[PrivateType]
    GetStaticArrayElement
    GetStaticField
    GetStaticProperty
    InvokeStatic
    SetStaticArrayElement
    SetStaticField
    SetStaticProperty




그 외 자잘한 거 2개 정도 더 정리해 볼까요? ^^

해당 메서드에서 예외가 발생할 수 있다면 이렇게 ExpectedException 특성을 지정할 수 있습니다.

[TestMethod]
[ExpectedException(typeof(FileNotFoundException))]
public void TestException()
{
    File.ReadAllText("test.dat");
}

그럼, FileNotFoundException 예외가 발생해도 기대했던 동작이기 때문에 위의 단위 테스트는 실패로 평가되지 않습니다.

마지막으로, 자신만의 메타데이터를 TestProperty를 이용해 설정하는 것이 가능합니다.

[TestMethod]
[TestProperty("Author", "kevin")]
public void ExampleTest()
{
    // Test logic
}

위와 같은 경우, "Test Explorer" 창에서 "Author [kevin]"이라는 별도의 출력 항목을 "Traits" 칼럼에서 확인할 수 있습니다.

testprop_attr_1.png

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/6/2021]

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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11831정성태3/4/201916743오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916435오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918166개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926052개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919011오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919199오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924385개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201918832오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920600오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918830오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919607오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922654오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201921945Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201919981VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916364오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919768Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918002오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201916838오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918269.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915527오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920672오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201918452.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201920525.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201921856디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201919766Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201919460디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...