dotnet / dotnet/MQTTnet

Problem with Hosted mqtt server via WebApplicationFactory

Open
#1,525 1 comment 0 reactions 0 assignees View on GitHub
question
Dominant language
C#
Stars
5.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

I have a problem with integration tests for a hosted mqtt server instance.
Program.cs:

```
builder.WebHost.UseKestrel(w =>
{
w.ListenAnyIP(mqttOptions.Port, l => l.UseMqtt());
w.ListenAnyIP(8100);
});
```
....
```
builder.Services.AddHostedMqttServer(mqttServer =>
{
mqttServer.WithDefaultEndpoint()
.WithDefaultEndpointPort(mqttOptions.Port)
.WithMaxPendingMessagesPerClient(mqttOptions.MaxPendingMessages)
.WithConnectionBacklog(100).WithTlsEndpointReuseAddress();
}).AddMqttConnectionHandler().AddConnections();
```
....
```
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("AllowAll");
endpoints.MapConnectionHandler(
"/ws",
httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
protocolList =>
protocolList.FirstOrDefault() ?? string.Empty);
});
```
Solution works correctly in normal usage but problem exists only in a integration tests when application is set up by `WebApplicationFactory()`.
Server shows `IsStarted` property as `true` and everything gets up correctly until I try to connect via client, then I receive this:

```
MQTTnet.Exceptions.MqttCommunicationException : Error while connecting with host '127.0.0.1:1883'.
---- System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it.
```

Can someone give me any advice where is the problem?

Nugets:

- MQTTnet 4.1.0.247
- MQTTnet.AspNetCore 4.1.0.247

Env:
- Asp .net core 6
- Windows

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the integration test that creates WebApplicationFactory and compare its hosted Kestrel listeners with the Program.cs MQTT configuration. Reproduce the connection attempt to 127.0.0.1:1883 and inspect the factory's effective port and server startup; done means the MQTT client connects successfully in the test environment.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
backend, networking, testing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.