آزمونهای یکپارچگی در برنامههای ASP.NET Core
نویسنده: وحید نصیری
تاریخ: ۱۳۹۹/۰۷/۱۶ ۱۰:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<NoWarn>RCS1090</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ASPNETCore2JwtAuthentication.WebApp\ASPNETCore2JwtAuthentication.WebApp.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="..\ASPNETCore2JwtAuthentication.WebApp\appsettings.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c329}" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="fluentassertions" Version="5.10.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.8" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.2" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.2" />
</ItemGroup>
</Project> using ASPNETCore2JwtAuthentication.WebApp;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
namespace ASPNETCore2JwtAuthentication.IntegrationTests
{
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
protected override IWebHostBuilder CreateWebHostBuilder()
{
var builder = base.CreateWebHostBuilder();
builder.ConfigureLogging(logging =>
{
//TODO: ...
});
return builder;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestServices(services =>
{
// Don't run `IHostedService`s when running as a test
services.RemoveAll(typeof(IHostedService));
});
}
}
} using System;
using System.Threading;
using System.Net.Http;
namespace ASPNETCore2JwtAuthentication.IntegrationTests
{
public static class TestsHttpClient
{
private static readonly Lazy<HttpClient> _serviceProviderBuilder =
new Lazy<HttpClient>(getHttpClient, LazyThreadSafetyMode.ExecutionAndPublication);
/// <summary>
/// A lazy loaded thread-safe singleton
/// </summary>
public static HttpClient Instance { get; } = _serviceProviderBuilder.Value;
private static HttpClient getHttpClient()
{
var services = new CustomWebApplicationFactory();
return services.CreateClient(); //NOTE: This action is very time consuming, so it should be defined as a singleton.
}
}
} using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ASPNETCore2JwtAuthentication.IntegrationTests
{
[TestClass]
public class JwtTests
{
[TestMethod]
public async Task TestLoginWorks()
{
// Arrange
var client = TestsHttpClient.Instance;
// Act
var token = await doLoginAsync(client);
// Assert
token.Should().NotBeNull();
token.AccessToken.Should().NotBeNullOrEmpty();
token.RefreshToken.Should().NotBeNullOrEmpty();
}
[TestMethod]
public async Task TestCallProtectedApiWorks()
{
// Arrange
var client = TestsHttpClient.Instance;
// Act
var token = await doLoginAsync(client);
// Assert
token.Should().NotBeNull();
token.AccessToken.Should().NotBeNullOrEmpty();
token.RefreshToken.Should().NotBeNullOrEmpty();
// Act
const string protectedApiUrl = "/api/MyProtectedApi";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
var response = await client.GetAsync(protectedApiUrl);
response.EnsureSuccessStatusCode();
// Assert
var responseString = await response.Content.ReadAsStringAsync();
responseString.Should().NotBeNullOrEmpty();
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var apiResponse = JsonSerializer.Deserialize<MyProtectedApiResponse>(responseString, options);
apiResponse.Title.Should().NotBeNullOrEmpty();
apiResponse.Title.Should().Be("Hello from My Protected Controller! [Authorize]");
}
private static async Task<Token> doLoginAsync(HttpClient client)
{
const string loginUrl = "/api/account/login";
var user = new { Username = "Vahid", Password = "1234" };
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Post, loginUrl)
{
Content = new StringContent(JsonSerializer.Serialize(user), Encoding.UTF8, "application/json")
});
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
responseString.Should().NotBeNullOrEmpty();
return JsonSerializer.Deserialize<Token>(responseString);
}
}
}
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="ProjName.Tests" />
</ItemGroup>
</Project>