Добавить тесты

This commit is contained in:
Roman Efremov 2024-11-12 18:02:09 +05:00
parent dc5a47d749
commit 9196dc1f9c
13 changed files with 291 additions and 53 deletions

View File

@ -7,6 +7,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExampleSignalR", "ExampleSi
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HubListener", "HubListener\HubListener.csproj", "{16E4F78D-5D80-4A9E-A817-1ABA6392DF91}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HubListener", "HubListener\HubListener.csproj", "{16E4F78D-5D80-4A9E-A817-1ABA6392DF91}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExampleSignalR.Test", "TestProject\ExampleSignalR.Test.csproj", "{D5D33655-9C04-440C-9C07-085C2C20D2A1}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -21,6 +23,10 @@ Global
{16E4F78D-5D80-4A9E-A817-1ABA6392DF91}.Debug|Any CPU.Build.0 = Debug|Any CPU {16E4F78D-5D80-4A9E-A817-1ABA6392DF91}.Debug|Any CPU.Build.0 = Debug|Any CPU
{16E4F78D-5D80-4A9E-A817-1ABA6392DF91}.Release|Any CPU.ActiveCfg = Release|Any CPU {16E4F78D-5D80-4A9E-A817-1ABA6392DF91}.Release|Any CPU.ActiveCfg = Release|Any CPU
{16E4F78D-5D80-4A9E-A817-1ABA6392DF91}.Release|Any CPU.Build.0 = Release|Any CPU {16E4F78D-5D80-4A9E-A817-1ABA6392DF91}.Release|Any CPU.Build.0 = Release|Any CPU
{D5D33655-9C04-440C-9C07-085C2C20D2A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D5D33655-9C04-440C-9C07-085C2C20D2A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D5D33655-9C04-440C-9C07-085C2C20D2A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D5D33655-9C04-440C-9C07-085C2C20D2A1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -4,9 +4,16 @@ namespace ExampleSignalR.Hubs
{ {
public class ChatHub : Hub public class ChatHub : Hub
{ {
private readonly IMessageService messageService;
public ChatHub(IMessageService messageService) {
this.messageService = messageService;
}
public async Task SendMessage(string user, string message) public async Task SendMessage(string user, string message)
{ {
await Clients.All.SendAsync("ReceiveMessage", user, message); var msg = messageService.GetMessage();
await Clients.All.SendAsync("ReceiveMessage", user, msg);
} }
} }
} }

View File

@ -0,0 +1,7 @@
namespace ExampleSignalR
{
public interface IMessageService
{
string GetMessage();
}
}

View File

@ -0,0 +1,10 @@
namespace ExampleSignalR
{
public class MessageService : IMessageService
{
public string GetMessage()
{
return "123";
}
}
}

View File

@ -1,36 +1,45 @@
using ExampleSignalR.Hubs; using ExampleSignalR.Hubs;
using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Http.Connections;
var builder = WebApplication.CreateBuilder(args); namespace ExampleSignalR;
// Add services to the container. public class Program
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{ {
app.UseExceptionHandler("/Error"); private static void Main(string[] args)
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. {
app.UseHsts(); var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddTransient<IMessageService, MessageService>();
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chatHub",
options =>
{
options.ApplicationMaxBufferSize = 128;
options.TransportMaxBufferSize = 128;
options.LongPolling.PollTimeout = TimeSpan.FromMinutes(1);
options.Transports = HttpTransportType.LongPolling | HttpTransportType.WebSockets;
});
app.Run();
}
} }
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.MapHub<ChatHub>("/chatHub",
options => {
options.ApplicationMaxBufferSize = 128;
options.TransportMaxBufferSize = 128;
options.LongPolling.PollTimeout = TimeSpan.FromMinutes(1);
options.Transports = HttpTransportType.LongPolling | HttpTransportType.WebSockets;
});
app.Run();

View File

@ -1,38 +1,38 @@
{ {
"$schema": "http://json.schemastore.org/launchsettings.json", //"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": { //"iisSettings": {
"windowsAuthentication": false, // "windowsAuthentication": false,
"anonymousAuthentication": true, // "anonymousAuthentication": true,
"iisExpress": { // "iisExpress": {
"applicationUrl": "http://localhost:57527", // "applicationUrl": "http://localhost:57527",
"sslPort": 44355 // "sslPort": 44355
} // }
}, //},
"profiles": { "profiles": {
"http": { //"http": {
"commandName": "Project", // "commandName": "Project",
"dotnetRunMessages": true, // "dotnetRunMessages": true,
"launchBrowser": true, // "launchBrowser": true,
"applicationUrl": "http://localhost:5114", // "applicationUrl": "http://localhost:5114",
"environmentVariables": { // "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" // "ASPNETCORE_ENVIRONMENT": "Development"
} // }
}, //},
"https": { "https": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"applicationUrl": "https://localhost:7083;http://localhost:5114", "applicationUrl": "https://localhost:7083",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
}, },
"IIS Express": { //"IIS Express": {
"commandName": "IISExpress", // "commandName": "IISExpress",
"launchBrowser": true, // "launchBrowser": true,
"environmentVariables": { // "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" // "ASPNETCORE_ENVIRONMENT": "Development"
} // }
} //}
} }
} }

View File

@ -1,4 +1,11 @@
{ {
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://localhost:7083"
}
}
},
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",

26
TestProject/AppFixture.cs Normal file
View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
namespace ExampleSignalR.Test
{
public class AppFixture
{
public const string BaseUrl = "http://localhost:54321";
static AppFixture()
{
var webhost = WebHost
.CreateDefaultBuilder(null)
.UseStartup<IStartup>()
.UseUrls(BaseUrl)
.Build();
webhost.Start();
}
}
}

View File

@ -0,0 +1,20 @@
using Microsoft.Extensions.DependencyInjection;
namespace ExampleSignalR.Test;
public abstract class BaseIntegrationTest : IClassFixture<WebAppFactoryFixture>,
IDisposable
{
protected readonly IServiceScope scope;
protected readonly WebAppFactoryFixture factory;
protected BaseIntegrationTest(WebAppFactoryFixture factory)
{
scope = factory.Services.CreateScope();
this.factory = factory;
}
public void Dispose()
{
scope.Dispose();
}
}

View File

@ -0,0 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.10" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.10" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ExampleSignalR\ExampleSignalR.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>

38
TestProject/UnitTest1.cs Normal file
View File

@ -0,0 +1,38 @@
using Microsoft.AspNetCore.SignalR.Client;
using static System.Net.WebRequestMethods;
using static Microsoft.AspNetCore.Http.StatusCodes;
namespace ExampleSignalR.Test;
public class UnitTest1 : BaseIntegrationTest
{
private readonly HttpClient _httpClient;
public UnitTest1(WebAppFactoryFixture factory) : base(factory)
{
_httpClient = factory.CreateClient();
}
[Fact]
public async void ConnectToSignalRHub()
{
var hubConnection = new HubConnectionBuilder()
.WithUrl($"{factory.url}/chatHub") // ...appsettings.json
.Build();
await hubConnection.StartAsync();
}
//public async Task Connect()
//{
// try
// {
// await hubConnection.StartAsync();
// Console.WriteLine("×àò ïîäêëþ÷åí...");
// }
// catch (Exception ex)
// {
// Console.WriteLine($"Îøèáêà ïîäêëþ÷åíèÿ: {ex.Message}");
// }
//}
}

View File

@ -0,0 +1,50 @@
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using static Microsoft.AspNetCore.Http.StatusCodes;
namespace ExampleSignalR.Test;
public class WebAppFactoryFixture : WebApplicationFactory<ExampleSignalR.Program>
{
public string url = "https://localhost:7083";
//private static readonly JsonSerializerOptions JsonSerializerOptions = new()
//{
//};
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(ConfigureServices);
//builder.UseEnvironment("Development");
builder.UseUrls(url);
base.ConfigureWebHost(builder);
}
private void ConfigureServices(IServiceCollection services)
{
//var t = services.Select(e => e.ServiceType == typeof(IMessageService));
services.RemoveAll(typeof(IMessageService));
services.AddTransient<IMessageService, MessageServiceT>();
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = Status307TemporaryRedirect;
options.HttpsPort = 7083;
});
}
}
public class MessageServiceT() : IMessageService
{
public string GetMessage()
{
return "321";
}
}

View File

@ -0,0 +1,16 @@
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://localhost:7083"
}
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}