I write simple test for my signalR app. I create fixture for web host and start connection to hub. Unfortunately in OnConnected hub method I read Context.User.Identity.Name which is null when I start test. How to configure authentication for my webhost fixture? I'd like to test scenario where few users are connected to hub. In Production mode user first sign in using /Account/LogIn controller method, then auth cookie is created and send with every request.
public class AppFixture
{
public const string BaseUrl = "http://localhost:54321";
static AppFixture()
{
var webhost = WebHost
.CreateDefaultBuilder(null)
.UseEnvironment("Testing")
.UseStartup<Startup>()
.UseUrls(BaseUrl)
.Build();
webhost.Start();
}
public string GetCompleteServerUrl(string route)
{
route = route?.TrimStart('/', '\\');
return $"{BaseUrl}/{route}";
}
}
public class DataHubTest
{
private readonly ITestOutputHelper output;
public DataHubTest( ITestOutputHelper output)
{
this.output = output;
}
private static async Task<HubConnection> StartConnectionAsync(string hubUrl)
{
HubConnection connection = new HubConnectionBuilder()
.WithUrl(hubUrl)
.Build();
await connection.StartAsync();
return connection;
}
[Fact]
public async Task HubConnectionEchoTestAsync()
{
// Arrange
var fixture = new AppFixture();
var url = fixture.GetCompleteServerUrl("/dataHub");
var connection = await StartConnectionAsync(url); //TODO: User Auth? => Context.User.Identity.Name
// using mock handler to verify return type and value
var handler = new Mock<Action<string>>();
connection.On("Echo", handler.Object);
// Act
await connection.SendAsync("echo", "Hello from testing method");
// Assert
handler.Verify(x => x(It.Is<string>(n => n == "Hello from testing method")), Times.Once());
}
public class DataHub: Hub {
//... skip rest of hub methods
public override Task OnConnectedAsync()
{
string name = Context.User.Identity.Name; // Here .Name is null when I run test
_connections.Add(name, Context.ConnectionId);
_logger.LogInformation("User: {User} has been connected to hub. ConnID: {connectionId}", name, Context.ConnectionId);
return base.OnConnectedAsync();
}
}