단위 테스트를 수행할 때 코드 커버리지는 코드 품질을 평가하는 중요한 지표로 활용된다. Azure DevOps의 빌드 파이프라인을 통해 자동으로 커버리지 결과를 생성하고 시각화하는 방법을 알아본다. Visual Studio Test Platform은 Coverlet 데이터 수집기를 내장하고 있어 별도 복잡한 설정 없이 바로 사용할 수 있다.
테스트 프로젝트 설정
단위 테스트 프로젝트에서 Coverlet 데이터 수집기를 사용하려면 coverlet.collector NuGet 패키지를 참조해야 한다. 아래는 테스트 프로젝트의 csproj 예시로, 측정 대상이 되는 비즈니스 로직 라이브러리를 참조하고 있다.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="1.3.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MyApp.Core\MyApp.Core.csproj" />
</ItemGroup>
</Project>
파이프라인 단계 구성
- NuGet 패키지 복원
빌드를 실행하기 전에 프로젝트의 모든 의존성 패키지를 복원한다.
- task: DotNetCoreCLI@2
displayName: 'Restore NuGet Packages'
inputs:
command: 'restore'
projects: '**/*.csproj'
- 프로젝트 빌드
소스 코드를 컴파일하여 빌드 산출물을 생성한다.
- task: DotNetCoreCLI@2
displayName: 'Build Solution'
inputs:
command: 'build'
arguments: '--configuration $(buildConfig) --no-restore'
- 단위 테스트 실행 및 커버리지 데이터 수집
테스트를 실행하면서 --collect "XPlat Code coverage" 인자를 전달하면 Cobertura 형식의 커버리지 파일이 생성된다.
- task: DotNetCoreCLI@2
displayName: 'Run Tests with Coverage'
inputs:
command: 'test'
projects: '**/MyApp.Tests.csproj'
arguments: '--configuration $(buildConfig) --collect:"XPlat Code coverage" /RunConfiguration.DisableAppDomain=true'
- ReportGenerator 전역 도구 설치
수집된 XML 커버리지 데이터를 읽기 쉬운 HTML 리포트로 변환하기 위해 ReportGenerator 도구를 설치한다.
- task: DotNetCoreCLI@2
displayName: 'Setup ReportGenerator Tool'
inputs:
command: 'custom'
custom: 'tool'
arguments: 'install -g dotnet-reportgenerator-globaltool'
- 커버리지 리포트 생성
임시 디렉터리에 저장된 coverage.cobertura.xml 파일을 원본으로 삼아 리포트를 출력한다.
- script: |
reportgenerator \
-reports:$(Agent.TempDirectory)/**/coverage.cobertura.xml \
-targetdir:$(Build.SourcesDirectory)/coverage-output \
-reporttypes:"Cobertura"
displayName: 'Generate Coverage Reports'
- Azure DevOps에 커버리지 결과 게시
생성된 리포트를 파이프라인 결과에 업로드하면 Azure DevOps UI에서 커버리지 탭을 통해 확인할 수 있다.
- task: PublishCodeCoverageResults@1
displayName: 'Upload Coverage Results'
inputs:
codeCoverageTool: 'Cobertura'
summaryFileLocation: '$(Build.SourcesDirectory)/coverage-output/Cobertura.xml'
pathToSources: '$(Build.SourcesDirectory)'
결과 확인
파이프라인 실행이 완료되면 빌드 요약 페이지의 "코드 커버리지" 탭에서 시각화된 리포트를 확인할 수 있다.
트러블슈팅
Linux 에이전트에서 reportgenerator 명령을 찾을 수 없는 경우
Linux 기반 빌드 에이전트를 사용할 때 dotnet-reportgenerator 명령을 인식하지 못하는 문제가 발생할 수 있다. 전역 도구를 설치한 후 PATH가 갱신되지 않아 발생하는 문제이므로, 아래 스크립트 태스크를 추가하여 PATH에 도구 경로를 추가해야 한다.
- task: Bash@3
displayName: 'Add Dotnet Tools to PATH'
inputs:
script: 'echo "##vso[task.prependpath]$HOME/.dotnet/tools"'
커버리지 배지 생성
Azure DevOps에서 제공하는 엔드포인트를 통해 README 등에 커버리지 배지를 삽입할 수 있다.
- 커버리지 비율 배지:
https://img.shields.io/azure-devops/coverage/{org}/{project}/{pipelineId}/{branch} - 테스트 통과 수 배지:
https://img.shields.io/azure-devops/tests/{org}/{project}/{pipelineId}/{branch}