Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Testavior is a lightweight solution to help you develop Behavior Tests for ASP.NET Core

License

NotificationsYou must be signed in to change notification settings

geeklearningio/Testavior

Repository files navigation

NuGet VersionNuGet VersionBuild Status

Testavior

Testavior is alightweight solution to help you developBehavior Tests forASP.NET Core.

Behavior Tests are a way of testing your application features applying different types of behaviors to cover afunctional scenario.

It provides a simple and efficient approach to write automated tests for your ASP.NET Core application.
For more information aboutBehavior Testing with ASP.NET Core, please take a look herehttp://geeklearning.io/a-different-approach-to-test-your-asp-net-core-application

Features

Testavior provides 2 libraries:

  • Testavior.Configuration: Helps you configure your application to easily integrate behavior tests for your scenarios.
  • Testavior: Provides a featured and highly configurable test environment for your behavior tests:
    • Configured Test WebHost
    • Configured authentication context
      • Test authentication middleware
      • Configurable test identity
      • Identity claims helper
    • Configured Entity Framework Core context using SQLite provider
    • Serialization helper to handle URL encoded content
    • Set of HTTP tools to handleCSRF protection (very useful to test edition scenarios)
    • Assertion helper

Installation

On your ASP.NET Core project

  • Install theGeekLearning.Testavior.Configuration nuget package
    > dotnet add package GeekLearning.Testavior.Configuration

On your .NET Core Unit Test project

  • Install theGeekLearning.Testavior nuget package
    > dotnet add package GeekLearning.Testavior
  • Add your ASP.NET Core web project as a project reference

Configuration

The Test environment provided byTestavior is based on aStartup Configuration Service that let you separate theProduction environment configuration from theTest environment configuration.This configuration service is represented by a contractIStartupConfigurationService which define 3 methods:Configure -ConfigureEnvironment - ConfigureService that have to be called within theStartup Routine to inject environment dependent configuration.

1 - In yourASP.NET Core project:

  • Add aStartupConfigurationService class (change name if you wish) to your web project.
  • Implement theIStartupConfigurationService interface (optionally, inherit fromDefaultStartupConfigurationService to use the default empty implementation)
  • Implement the configuration specific to the Production environment and which must not be executed in the Test environment:
    • ConfigureServices: implement the configuration options that are specific to the Production environment
    • Configure: implement themiddleware configuration specific to the Production environment
    • ConfigureEnvironment: implement what has to be executed before anything

Sample:

publicclassStartupConfigurationService:DefaultStartupConfigurationService{publicoverridevoidConfigureServices(IServiceCollectionservices,IConfigurationRootconfiguration){base.ConfigureServices(services,configuration);varconnection="CONNECTION_STRING";services.AddDbContext<[EF_DB_CONTEXT]>(options=>options.UseSqlServer(connection));}}

2 - In yourProgram class:
Inject yourStartupConfigurationService by calling theConfigureStartup method on yourWebHostBuilder:

newWebHostBuilder()   ....UseStartup<Startup>().ConfigureStartup<StartupConfigurationService>()

3 - In yourStartup class:

  • Inject theIStartupConfigurationService interface into theStartup class
  • Call theConfigureEnvironment method at the end of theStartup constructor
  • Call theConfigureServices method at the end of the originalStartup.ConfigureServices method
  • Call theConfigure method at the beginning of the originalStartup.Configure method

Sample:

publicclassStartup{privateIStartupConfigurationServiceexternalStartupConfiguration;publicStartup(IHostingEnvironmentenv,IStartupConfigurationServiceexternalStartupConfiguration=null){this.externalStartupConfiguration=externalStartupConfiguration;this.externalStartupConfiguration.ConfigureEnvironment(env);}publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc()// Pass configuration (IConfigurationRoot) to the configuration service if needed       this.externalStartupConfiguration.ConfigureServices(services,null);}publicvoidConfigure(IApplicationBuilderapp,IHostingEnvironmentenv,ILoggerFactoryloggerFactory){this.externalStartupConfiguration.Configure(app,env,loggerFactory);app.UseMvc();}}

4 - In your test project file:
TheRazor engine uses dependency files (.deps.json) to resolve some references at runtime. So in order to test theMVC part of a application, it is necessary to import these files. To do it, add the following section to your.csproj:

<TargetName="CopyDepsFiles"AfterTargets="Build"Condition="'$(TargetFramework)'!=''">    <ItemGroup>      <DepsFilePathsInclude="$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))" />    </ItemGroup>    <CopySourceFiles="%(DepsFilePaths.FullPath)"DestinationFolder="$(OutputPath)"Condition="Exists('%(DepsFilePaths.FullPath)')" /></Target>

5 - ForxUnit users
If you intend to use xUnit, first follow theofficial documention, then add axunit.runner.json file to your test project:

{"shadowCopy":false}

and add the following section to your.csproj:

<ItemGroup>  <NoneInclude="xunit.runner.json"CopyToOutputDirectory="PreserveNewest" /></ItemGroup>

Writing Tests

A specificIStartupConfigurationService is required for theTest environment if you want to implementTest Specific configuration.
Testavior comes with a test specificIStartupConfigurationService implementation:TestStartupConfigurationService which provide aTest Environment full of useful features (seeFeatures section).
Of course you can implement your own Startup configuration service (by using the onboardTestStartupConfigurationService or not).

To create aTest Environment, just instanciate theTestEnvironment class by passing it your ASP.NET Core applicationStartup, yourIStartupConfigurationService implementation, the type of your EF Core ObjectContext and the relative path to your ASP.NET Core project (required to resolve MVC views).

vartestEnvironment=newTestEnvironment<Startup,TestStartupConfigurationService<[EF_DB_CONTEXT]>>(Path.Combine(System.AppContext.BaseDirectory,@"[PATH_TO_WEB_APP]"));

API Test

Write your API test by just sending web requests using theTest Environment:

[TestMethod]publicvoidScenarioShouldBeOk(){vartestEnvironment=newTestEnvironment<Startup,TestStartupConfigurationService<[EF_DB_CONTEXT]>>(Path.Combine(System.AppContext.BaseDirectory,@"[PATH_TO_WEB_APP]"));varresponse=testEnvironment.Client.GetAsync("/api/data").Result;response.EnsureSuccessStatusCode();// Test result contentvarresult=JsonConvert.DeserializeObject<Data[]>(response.Content.ReadAsStringAsync().Result);Assert.AreEqual("data",result.Data);}

MVC Test

Write a MVC test is almost as easy as testing an API except that you might want to test theModel returned by the server and not theView.
To do that,Testavior provides aViewModel Repository that will intercept and store the view's models returned by the server.

You can access to the this repository using the ASP.NET Core dependency injection mechanism:

[TestMethod]publicvoidScenarioShouldBeOk(){vartestEnvironment=newTestEnvironment<Startup,TestStartupConfigurationService<[EF_DB_CONTEXT]>>(Path.Combine(System.AppContext.BaseDirectory,@"[PATH_TO_WEB_APP]"));testEnvironment.Client.GetAsync("/").Result.EnsureSuccessStatusCode();varviewModel=testEnvironment.ServiceProvider.GetRequiredService<ViewModelRepository>().Get<[VIEWMODEL_TYPE]>();Assert.AreEqual("data",viewModel.Data);}

And feel free to take a look at theSamples section ;)

Happy testing ! :)

About

Testavior is a lightweight solution to help you develop Behavior Tests for ASP.NET Core

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors3

  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp