Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
Visual Studio 2010 - Code Coverage 결과를 외부 XML 파일로 출력하는 명령행 도구 제작

Visual Studio 2010에서 Code Coverage를 수행하면 다음과 같이 내부 "Code Coverage Results" 윈도우에서 그 결과를 확인해 볼 수 있는데요.

how_to_export_code_coverage_result_1.png

위와 같은 결과물은 로컬 상에 "[파일명].coverage"라는 이름으로 저장되어 있긴 한데, 애석하게도 바이너리 형식이라서 임의로 활용하는 것이 쉽지 않습니다. 물론, 위의 화면 자체에서 제공되는 "Export Results" 버튼을 이용해서 곧바로 XML 파일로 변환해서 보관하는 것이 가능하지만, 자동화된 빌드 시스템에서 코드 커버리지 결과도 함께 연동하고 싶을 때는 이렇게 UI를 통해서 하는 것은 전혀 도움이 되지 않습니다.

즉, "명령행"에서 빌드 및 테스트 수행 결과로 생성된 .coverage 파일을 "Export Results"와 동일한 형식의 XML로 변환하는 것이 해결 과제입니다.




다행히, Visual Studio는 ".coverage" 파일을 코드로 다룰 수 있도록 허용해 주고 있는데요. 이에 관해서는 다음의 글에서 설명해 주고 있습니다.

Is it possible to programmatically access code coverage data? 
; http://www.go4answers.com/Example/possible-programmatically-access-code-4285.aspx

위의 글에서는 "Visual Studio 2008"로 되어 있지만, 여기서는 "Visual Studio 2010"을 기준으로 설명합니다.

1. 새 프로젝트를 생성하고, "Microsoft.VisualStudio.Coverage.Analysis.dll"을 참조.


Microsoft.VisualStudio.Coverage.Analysis.dll 파일은 기본적으로 참조 대화상자에 나오지 않기 때문에, "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies" 경로로 직접 찾아들어가야 합니다.

2. "Microsoft.VisualStudio.Coverage.Symbols.dll" 파일 추가

Microsoft.VisualStudio.Coverage.Analysis.dll 파일과 동일한 폴더("C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies")에 있는 "Microsoft.VisualStudio.Coverage.Symbols.dll" 파일을 추가합니다. "참조"가 아니라 그냥 파일 추가를 하고 속성 창에서 다음과 같이 설정을 해줍니다.

how_to_export_code_coverage_result_2.png

Build Action: None
Copy to Output Directory: Copy if newer


3. 코드 추가


Visual Studio 2010에서는 "Is it possible to programmatically access code coverage data?" 글에서 설명하고 있는 개체 모델이 다소 변경이 되었습니다. 따라서 다음과 같은 식으로 코딩을 해주어야 합니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.VisualStudio.Coverage.Analysis;
using System.IO;

namespace CodeCoverageExporter
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("[example]");
                Console.WriteLine("\tCodeCoverageExporter.exe [exepath] [sympath] [coveragefilepath] [outputfilepath]");
                return;
            }

            string binaryPath = args[0];
            string symPath = args[1];
            string coverageFilePath = args[2];
            string outputPath = args[3];

            List symPaths = new List();
            List binaryPaths = new List();
            symPaths.Add(symPath);
            binaryPaths.Add(binaryPath);

            CoverageInfo coverageInfo = CoverageInfo.CreateFromFile(
                coverageFilePath, binaryPaths, symPaths);

            string exportFilePath = Path.Combine(Environment.CurrentDirectory, outputPath);

            CoverageDS data = coverageInfo.BuildDataSet();
            data.WriteXml(exportFilePath);
            // 또는 결과 XML 파일을 VS IDE에서 읽어들여야 한다면 아래와 같이 실행.
            // data.WriteXml(exportFilePath, System.Data.XmlWriteMode.WriteSchema);
        }
    }
}

[exepath]와 [sympath]는 보통 단위 테스트 했을 때 나오는 "TestResults"의 "Out" 폴더인데요. 예를 들면 다음과 같이 "*.instr.pdb" 파일들이 놓인 경로를 가리켜야 합니다.

how_to_export_code_coverage_result_3.png

[coveragefilepath]는 코드 커버리지 결과를 담고 있는 "[파일명].coverage"의 경로입니다. 이 파일은 단위 테스트 했을 때 보통 "TestResults"의 "In" 폴더에 "data.coverage"라는 이름으로 놓이게 됩니다.

how_to_export_code_coverage_result_4.png

마지막으로 [outputfilepath]는 새로 출력될 XML 파일의 경로를 적어주면 됩니다.

이제 빌드하고, 적절한 테스트 환경을 구성해서 실행해 보면 "Visual Studio 2010"의 "Code Coverage Results" 화면에서 "Export Results" 했을 때와 동일한 형식의 xml 파일이 생성되는 것을 확인할 수 있습니다.

첨부된 압축 파일은 위의 소스 코드를 포함한 프로젝트입니다.




참고로, "Is it possible to programmatically access code coverage data?" 글에서도 나오고 있지만, 만약 다음과 같은 오류가 발생한다면,

Unhandled Exception: Microsoft.VisualStudio.Coverage.Analysis.CoverageAnalysisException: Unable to load DLL 'Microsoft.VisualStudio.Coverage.Symbols.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) ---> System.DllNotFoundException: Unable to load DLL 'Microsoft.VisualStudio.Coverage.Symbols.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at Microsoft.VisualStudio.Coverage.Analysis.Vsp.SymbolInterop.CreateSession()
at Microsoft.VisualStudio.Coverage.Analysis.Vsp.VspSymbolReader..ctor(StringsymbolSearchPath, String expectedPath, String actualPath, UInt32 imageSize, MissingFileCallback callback)
at Microsoft.VisualStudio.Coverage.Analysis.Vsp.VspSymbolReaderFactory.CreateReader()
at Microsoft.VisualStudio.Coverage.Analysis.CoverageInfo.BuildDataSet(Boolean summaryOnly, IEnumerable`1 tests, IEnumerable`1 modules)
--- End of inner exception stack trace ---
at Microsoft.VisualStudio.Coverage.Analysis.CoverageInfo.BuildDataSet(Boolean summaryOnly, IEnumerable`1 tests, IEnumerable`1 modules)
at Microsoft.VisualStudio.Coverage.Analysis.CoverageInfo.BuildDataSet()
at CodeCoverageExporter.Program.Main(String[] args) in D:\...\Program.cs:line 37


원인은, "Microsoft.VisualStudio.Coverage.Symbols.dll" 파일을 실행 파일과 동일한 폴더에 놓지 않아서 발생하는 것입니다.



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/28/2023]

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

비밀번호

댓글 작성자
 



2010-09-08 10시44분
Developer Tool Manager (1.0.1.12) 버전에 추가했습니다. ^^ (Visual Studio 탭 - CodeCoverageExporter)
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=-

kevin25

1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13569정성태2/28/20241785닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241916닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241859오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241935오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241807닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241984Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241962디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20242014오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20242088닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20242132디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242956오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242212닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241948Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20242007Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20242154닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241876VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241971닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241918닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242108닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242271Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242737개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242535개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242321개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20242162Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20242010닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20242035오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...