TestAvior 는 ASP.NET Core 의 행동 테스트를 개발하는 데 도움이되는 가벼운 솔루션입니다.
행동 테스트는 기능 시나리오를 다루기 위해 다양한 유형의 동작을 적용하는 응용 프로그램 기능을 테스트하는 방법입니다.
ASP.NET Core 응용 프로그램에 대한 자동 테스트를 작성하는 간단하고 효율적인 접근 방식을 제공합니다.
ASP.NET Core를 사용한 행동 테스트 에 대한 자세한 내용은 http://geeklearning.io/a-different-acko-test-your-asp-net-core-application을 참조하십시오.
testavior는 2 개의 라이브러리를 제공합니다.
ASP.NET Core 프로젝트에서
> dotnet add package GeekLearning.Testavior.Configuration
.NET Core Unit Test 프로젝트에서
> dotnet add package GeekLearning.Testavior
TestAvior 에서 제공하는 테스트 환경은 프로덕션 환경 구성을 테스트 환경 구성과 분리 할 수있는 시작 구성 서비스를 기반으로합니다. 이 구성 서비스는 3 가지 방법을 정의하는 계약 IStartupConfigurationService 로 표시됩니다. Configure - ConfigureEnvironment - ConfigureService 종속 구성을 주입하기 위해 시작 루틴 내에서 호출되어야하는 구성 서비스를 정의합니다.
1- ASP.NET Core 프로젝트 :
StartupConfigurationService 클래스 (원하는 경우 이름 변경)를 추가하십시오.IStartupConfigurationService 인터페이스를 구현하십시오 (선택적으로 기본적으로 비어있는 구현을 사용하려면 DefaultStartupConfigurationService 에서 상속).ConfigureServices : 생산 환경에 특정한 구성 옵션 구현Configure : 생산 환경에 맞는 미들웨어 구성 구현ConfigureEnvironment : 무엇이든 실행해야 할 내용을 구현하십시오.견본:
public class StartupConfigurationService : DefaultStartupConfigurationService
{
public override void ConfigureServices ( IServiceCollection services , IConfigurationRoot configuration )
{
base . ConfigureServices ( services , configuration ) ;
var connection = "CONNECTION_STRING" ;
services . AddDbContext < [ EF_DB_CONTEXT ] > ( options =>
options . UseSqlServer ( connection ) ) ;
}
} 2- 프로그램 수업에서 :
WebHostBuilder 에서 ConfigureStartup 메소드를 호출하여 StartupConfigurationService 주입하십시오.
new WebHostBuilder ( )
.. .
. UseStartup < Startup > ( )
. ConfigureStartup < StartupConfigurationService > ( ) 3- Startup 클래스 :
IStartupConfigurationService 인터페이스를 Startup 클래스에 주입하십시오Startup 생성기 끝에 ConfigureEnvironment 메소드를 호출하십시오.Startup.ConfigureServices method의 끝에서 ConfigureServices 메소드를 호출하십시오.Startup.Configure 메소드의 시작 부분에서 Configure 메소드를 호출하십시오.견본:
public class Startup
{
private IStartupConfigurationService externalStartupConfiguration ;
public Startup ( IHostingEnvironment env , IStartupConfigurationService externalStartupConfiguration = null )
{
this . externalStartupConfiguration = externalStartupConfiguration ;
this . externalStartupConfiguration . ConfigureEnvironment ( env ) ;
}
public void ConfigureServices ( IServiceCollection services )
{
services . AddMvc ( )
// Pass configuration (IConfigurationRoot) to the configuration service if needed
this . externalStartupConfiguration . ConfigureServices ( services , null ) ;
}
public void Configure ( IApplicationBuilder app , IHostingEnvironment env , ILoggerFactory loggerFactory )
{
this . externalStartupConfiguration . Configure ( app , env , loggerFactory ) ;
app . UseMvc ( ) ;
}
} 4- 테스트 프로젝트 파일에서 :
Razor 엔진은 종속성 파일 (.deps.json)을 사용하여 런타임에서 일부 참조를 해결합니다. 따라서 응용 프로그램의 MVC 부분을 테스트하려면 이러한 파일을 가져와야합니다. 이를 위해 다음 섹션을 .csproj 에 추가하십시오.
< Target Name = " CopyDepsFiles " AfterTargets = " Build " Condition = " '$(TargetFramework)'!='' " >
< ItemGroup >
< DepsFilePaths Include = " $([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json')) " />
</ ItemGroup >
< Copy SourceFiles = " %(DepsFilePaths.FullPath) " DestinationFolder = " $(OutputPath) " Condition = " Exists('%(DepsFilePaths.FullPath)') " />
</ Target > 5- Xunit 사용자의 경우
Xunit을 사용하려면 먼저 공식 문서를 따르고 xunit.runner.json 파일을 테스트 프로젝트에 추가하십시오.
{
"shadowCopy" : false
} 다음 섹션을 .csproj 에 추가하십시오.
< ItemGroup >
< None Include = " xunit.runner.json " CopyToOutputDirectory = " PreserveNewest " />
</ ItemGroup > 테스트 특정 구성을 구현하려면 테스트 환경에 특정 IStartupConfigurationService 필요합니다.
TestAvior 에는 유용한 기능으로 가득 찬 테스트 환경을 제공하는 TestStartupConfigurationService ) 테스트 별 IStartupConfigurationService 구현이 제공됩니다 ( 기능 섹션 참조).
물론 자체 시작 구성 서비스를 구현할 수 있습니다 (Onboard TestStartupConfigurationService 를 사용하여).
테스트 환경을 만들려면 ASP.NET Core 애플리케이션 Startup , IStartupConfigurationService 구현, EF Core ObjectContext 유형 및 ASP.NET Core 프로젝트의 상대 경로 (MVC 뷰를 해결하는 데 필요한)를 전달하여 TestEnvironment 클래스를 통과시킵니다.
var testEnvironment = new TestEnvironment < Startup , TestStartupConfigurationService < [ EF_DB_CONTEXT ] > > (
Path . Combine ( System . AppContext . BaseDirectory , @"[PATH_TO_WEB_APP]" ) ) ; 테스트 환경을 사용하여 웹 요청을 보내면 API 테스트를 작성하십시오.
[ TestMethod ]
public void ScenarioShouldBeOk ( )
{
var testEnvironment = new TestEnvironment < Startup , TestStartupConfigurationService < [ EF_DB_CONTEXT ] > > (
Path . Combine ( System . AppContext . BaseDirectory , @"[PATH_TO_WEB_APP]" ) ) ;
var response = testEnvironment . Client . GetAsync ( "/api/data" ) . Result ;
response . EnsureSuccessStatusCode ( ) ;
// Test result content
var result = JsonConvert . DeserializeObject < Data [ ] > ( response . Content . ReadAsStringAsync ( ) . Result ) ;
Assert . AreEqual ( "data" , result . Data ) ;
} MVC 테스트 작성은 보기 가 아닌 서버에서 반환 한 모델을 테스트 할 수 있다는 점을 제외하고 API를 테스트하는 것만 큼 쉽습니다.
이를 위해 TestAvior는 서버가 반환 한 뷰의 모델을 가로 채고 저장하는 뷰 모델 리포지토리를 제공합니다.
ASP.NET Core Dependency Injection Mechanism을 사용 하여이 저장소에 액세스 할 수 있습니다.
[ TestMethod ]
public void ScenarioShouldBeOk ( )
{
var testEnvironment = new TestEnvironment < Startup , TestStartupConfigurationService < [ EF_DB_CONTEXT ] > > (
Path . Combine ( System . AppContext . BaseDirectory , @"[PATH_TO_WEB_APP]" ) ) ;
testEnvironment . Client . GetAsync ( "/" ) . Result . EnsureSuccessStatusCode ( ) ;
var viewModel = testEnvironment
. ServiceProvider
. GetRequiredService < ViewModelRepository > ( )
. Get < [ VIEWMODEL_TYPE ] > ( ) ;
Assert . AreEqual ( "data" , viewModel . Data ) ;
}샘플 섹션을 자유롭게 살펴보십시오.)
행복한 테스트! :)