- Notifications
You must be signed in to change notification settings - Fork5
Testavior is a lightweight solution to help you develop Behavior Tests for ASP.NET Core
License
geeklearningio/Testavior
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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
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
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
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 a
StartupConfigurationService
class (change name if you wish) to your web project. - Implement the
IStartupConfigurationService
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 environmentConfigure
: implement themiddleware configuration specific to the Production environmentConfigureEnvironment
: 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 the
IStartupConfigurationService
interface into theStartup
class - Call the
ConfigureEnvironment
method at the end of theStartup
constructor - Call the
ConfigureServices
method at the end of the originalStartup.ConfigureServices
method - Call the
Configure
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>
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]"));
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);}
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
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors3
Uh oh!
There was an error while loading.Please reload this page.