{"id":13431851,"url":"https://github.com/geeklearningio/Testavior","last_synced_at":"2025-03-16T22:32:38.890Z","repository":{"id":57957164,"uuid":"66013377","full_name":"geeklearningio/Testavior","owner":"geeklearningio","description":"Testavior is a lightweight solution to help you develop Behavior Tests for ASP.NET Core","archived":false,"fork":false,"pushed_at":"2023-04-17T10:20:54.000Z","size":1892,"stargazers_count":41,"open_issues_count":4,"forks_count":5,"subscribers_count":7,"default_branch":"develop","last_synced_at":"2024-10-03T11:05:46.776Z","etag":null,"topics":["aspnet","aspnetcore","devops","dotnet","dotnet-core","testing"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/geeklearningio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2016-08-18T16:32:18.000Z","updated_at":"2022-07-23T22:12:50.000Z","dependencies_parsed_at":"2024-01-05T21:03:28.738Z","dependency_job_id":null,"html_url":"https://github.com/geeklearningio/Testavior","commit_stats":null,"previous_names":["geeklearningio/gl-dotnet-test-integration"],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/geeklearningio%2FTestavior","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/geeklearningio%2FTestavior/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/geeklearningio%2FTestavior/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/geeklearningio%2FTestavior/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/geeklearningio","download_url":"https://codeload.github.com/geeklearningio/Testavior/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221668940,"owners_count":16860763,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aspnet","aspnetcore","devops","dotnet","dotnet-core","testing"],"created_at":"2024-07-31T02:01:06.468Z","updated_at":"2024-10-27T11:30:28.896Z","avatar_url":"https://github.com/geeklearningio.png","language":"C#","readme":"[![NuGet Version](http://img.shields.io/nuget/v/GeekLearning.Testavior.svg?style=flat-square\u0026label=NuGet:%20Testavior)](https://www.nuget.org/packages/GeekLearning.Testavior/)\n[![NuGet Version](http://img.shields.io/nuget/v/GeekLearning.Testavior.Configuration.svg?style=flat-square\u0026label=NuGet:%20Testavior.Configuration)](https://www.nuget.org/packages/GeekLearning.Testavior.Configuration/)\n[![Build Status](https://geeklearning.visualstudio.com/_apis/public/build/definitions/f841b266-7595-4d01-9ee1-4864cf65aa73/62/badge)](#)\n# Testavior\n*Testavior* is a [lightweight solution](https://www.nuget.org/packages?q=Testavior) to help  you develop **Behavior** Tests for **ASP.NET Core**.  \n\n\u003eBehavior Tests are a way of testing your application features applying different types of behaviors to cover a **functional scenario**.  \n\nIt provides a simple and efficient approach to write automated tests for your ASP.NET Core application.  \nFor more information about *Behavior Testing* with ASP.NET Core, please take a look here http://geeklearning.io/a-different-approach-to-test-your-asp-net-core-application  \n \n### Features\n*Testavior* provides 2 libraries:\n* **Testavior.Configuration**: Helps you configure your application to easily integrate behavior tests for your scenarios.\n* **Testavior**: Provides a featured and highly configurable test environment for your behavior tests:\n  * Configured Test WebHost\n  * Configured authentication context\n    * Test authentication middleware \n    * Configurable test identity\n    * Identity claims helper\n  * Configured Entity Framework Core context using SQLite provider \n  * Serialization helper to handle URL encoded content \n  * Set of HTTP tools to handle *CSRF* protection (very useful to test edition scenarios)\n  * Assertion helper\n\n### Installation\nOn your ASP.NET Core project\n* Install the **GeekLearning.Testavior.Configuration** nuget package\n  ```\n  \u003e dotnet add package GeekLearning.Testavior.Configuration\n  ```\n\nOn your .NET Core Unit Test project\n* Install the **GeekLearning.Testavior** nuget package\n  ```\n  \u003e dotnet add package GeekLearning.Testavior\n  ```\n* Add your ASP.NET Core web project as a project reference\n### Configuration\nThe Test environment provided by *Testavior* is based on a **Startup Configuration Service** that let you separate the **Production** environment configuration from the **Test** environment configuration.\nThis configuration service is represented by a contract `IStartupConfigurationService` which define 3 methods: `Configure` - `ConfigureEnvironment -  ConfigureService` that have to be called within the **Startup Routine** to inject environment dependent configuration.  \n\n1 - In your **ASP.NET Core** project:\n* Add a `StartupConfigurationService` class (change name if you wish) to your web project.\n* Implement the `IStartupConfigurationService` interface (optionally, inherit from `DefaultStartupConfigurationService` to use the default empty implementation)\n* Implement the configuration specific to the Production environment and which must not be executed in the Test environment:\n  * `ConfigureServices`: implement the configuration options that are specific to the Production environment\n  * `Configure`: implement the *middleware* configuration specific to the Production environment\n  * `ConfigureEnvironment`: implement what has to be executed before anything\n\n Sample:\n ```csharp\n public class StartupConfigurationService : DefaultStartupConfigurationService\n{\n    public override void ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)\n    {\n        base.ConfigureServices(services, configuration);\n\n        var connection = \"CONNECTION_STRING\";\n            \n        services.AddDbContext\u003c[EF_DB_CONTEXT]\u003e(options =\u003e\n            options.UseSqlServer(connection));\n    }\n}\n ```\n \n 2 - In your **Program** class:  \n Inject your `StartupConfigurationService` by calling the `ConfigureStartup` method on your `WebHostBuilder`:\n ```csharp\n new WebHostBuilder()\n    ...\n    .UseStartup\u003cStartup\u003e()\n    .ConfigureStartup\u003cStartupConfigurationService\u003e()\n ```\n\n 3 - In your `Startup` class:\n * Inject the `IStartupConfigurationService` interface into the `Startup` class\n * Call the `ConfigureEnvironment` method at the end of the `Startup` constructor\n * Call the `ConfigureServices` method at the end of the original `Startup.ConfigureServices` method\n * Call the `Configure` method at the beginning of the original `Startup.Configure` method\n \n Sample:\n ```csharp\npublic class Startup\n{\n    private IStartupConfigurationService externalStartupConfiguration;\n\n    public Startup(IHostingEnvironment env, IStartupConfigurationService externalStartupConfiguration = null)\n    {\n        this.externalStartupConfiguration = externalStartupConfiguration;\n        this.externalStartupConfiguration.ConfigureEnvironment(env);\n    }\n\n    public void ConfigureServices(IServiceCollection services)\n    {\n        services.AddMvc()\n\n        // Pass configuration (IConfigurationRoot) to the configuration service if needed\n        this.externalStartupConfiguration.ConfigureServices(services, null);\n    }\n\n    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)\n    {\n        this.externalStartupConfiguration.Configure(app, env, loggerFactory);\n\n        app.UseMvc();\n    }\n}\n```\n\n4 - In your test project file:  \nThe **Razor** engine uses dependency files (.deps.json) to resolve some references at runtime. So in order to test the **MVC** part of a application, it is necessary to import these files. To do it, add the following section to your `.csproj`:\n```xml\n\u003cTarget Name=\"CopyDepsFiles\" AfterTargets=\"Build\" Condition=\"'$(TargetFramework)'!=''\"\u003e\n    \u003cItemGroup\u003e\n      \u003cDepsFilePaths Include=\"$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))\" /\u003e\n    \u003c/ItemGroup\u003e\n\n    \u003cCopy SourceFiles=\"%(DepsFilePaths.FullPath)\" DestinationFolder=\"$(OutputPath)\" Condition=\"Exists('%(DepsFilePaths.FullPath)')\" /\u003e\n\u003c/Target\u003e\n```\n\n5 - For **xUnit** users  \nIf you intend to use xUnit, first follow the [official documention](https://xunit.github.io/docs/getting-started-dotnet-core), then add a `xunit.runner.json` file to your test project:\n```json\n{\n  \"shadowCopy\": false\n}\n```\nand add the following section to your `.csproj`:\n```xml\n\u003cItemGroup\u003e\n  \u003cNone Include=\"xunit.runner.json\" CopyToOutputDirectory=\"PreserveNewest\" /\u003e\n\u003c/ItemGroup\u003e\n```\n\n### Writing Tests\nA specific `IStartupConfigurationService` is required for the **Test** environment if you want to implement **Test Specific** configuration.  \n*Testavior* comes with a test specific `IStartupConfigurationService` implementation: `TestStartupConfigurationService` which provide a **Test Environment** full of useful features (see **Features** section).  \nOf course you can implement your own Startup configuration service (by using the onboard `TestStartupConfigurationService` or not).  \n\nTo create a *Test Environment*, just instanciate the `TestEnvironment` class by passing it your ASP.NET Core application `Startup`, your `IStartupConfigurationService` implementation, the type of your EF Core ObjectContext and the relative path to your ASP.NET Core project (required to resolve MVC views).\n```csharp\nvar testEnvironment = new TestEnvironment\u003cStartup, TestStartupConfigurationService\u003c[EF_DB_CONTEXT]\u003e\u003e(\n    Path.Combine(System.AppContext.BaseDirectory, @\"[PATH_TO_WEB_APP]\"));\n```\n\n#### API Test\nWrite your API test by just sending web requests using the *Test Environment*:\n```csharp\n[TestMethod]\npublic void ScenarioShouldBeOk()\n{\n    var testEnvironment = new TestEnvironment\u003cStartup, TestStartupConfigurationService\u003c[EF_DB_CONTEXT]\u003e\u003e(\n       Path.Combine(System.AppContext.BaseDirectory, @\"[PATH_TO_WEB_APP]\"));\n\n    var response = testEnvironment.Client.GetAsync(\"/api/data\").Result;\n    response.EnsureSuccessStatusCode();\n\n    // Test result content\n    var result = JsonConvert.DeserializeObject\u003cData[]\u003e(response.Content.ReadAsStringAsync().Result);\n\n    Assert.AreEqual(\"data\", result.Data);\n}\n```\n\n#### MVC Test\nWrite a MVC test is almost as easy as testing an API except that you might want to test the **Model** returned by the server and not the **View**.  \nTo do that, *Testavior* provides a **ViewModel Repository** that will intercept and store the view's models returned by the server.\n\nYou can access to the this repository using the ASP.NET Core dependency injection mechanism:\n\n```csharp\n[TestMethod]\npublic void ScenarioShouldBeOk()\n{\n    var testEnvironment = new TestEnvironment\u003cStartup, TestStartupConfigurationService\u003c[EF_DB_CONTEXT]\u003e\u003e(\n       Path.Combine(System.AppContext.BaseDirectory, @\"[PATH_TO_WEB_APP]\"));\n\n    testEnvironment.Client.GetAsync(\"/\").Result.EnsureSuccessStatusCode();\n\n    var viewModel = testEnvironment\n                        .ServiceProvider\n                        .GetRequiredService\u003cViewModelRepository\u003e()\n                        .Get\u003c[VIEWMODEL_TYPE]\u003e();\n\n    Assert.AreEqual(\"data\", viewModel.Data);\n}\n```\n\nAnd feel free to take a look at the [Samples](https://github.com/geeklearningio/gl-dotnet-test-integration/tree/develop/sample) section ;)\n\nHappy testing ! :)","funding_links":[],"categories":["Frameworks, Libraries and Tools","框架, 库和工具"],"sub_categories":["Testing","测试"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgeeklearningio%2FTestavior","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgeeklearningio%2FTestavior","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgeeklearningio%2FTestavior/lists"}