Reputation: 2728
How do I use xUnit Assert.RaisesAny()? I can't seem to find any examples.
I received the following syntax error
The event 'IMqttServer.Started' can only appear on the left hand side of += or -=
This makes sense since I am not subscribing to it but I don't know what syntax to use with RaisesAny()
Basically, I am just trying to check that the Broker started, an at least 1 client connected to it and that it stopped.
P.S. MqttServer is an Mqtt Broker implementation that is part of MqttNet
here is my Test
public class ResearchTestingOnly
{
private readonly ITestOutputHelper output;
public ResearchTestingOnly(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void Test1()
{
IMqttServer _mqttBroker = new MqttFactory().CreateMqttServer();
var receivedEvents = new List<string>();
_mqttBroker.ClientConnected += delegate (object sender, MqttClientConnectedEventArgs args)
{
receivedEvents.Add(args.ClientId);
};
Assert.RaisesAny<EventHandler>(_mqttBroker.Started);
Assert.RaisesAny<MqttClientConnectedEventArgs>(_mqttBroker.ClientConnected);
Assert.RaisesAny<EventHandler>(_mqttBroker.Stopped);
//** Start Broker
Task _brokerTask = Task.Run(() => _mqttBroker.StartAsync(new MqttServerOptions()));
//** Wait 10 Seconds
var pause = new ManualResetEvent(false);
pause.WaitOne(10000);
//** Stop Broker
Task _brokerStopTask = Task.Run(() => _mqttBroker.StopAsync());
//** Wait for Broker Tasks to Complete
Task.WaitAll(_brokerTask, _brokerStopTask);
output.WriteLine($"Number of Clients Connected: {receivedEvents.Count}");
foreach(var b in receivedEvents)
{
output.WriteLine(b);
}
}
}
Upvotes: 3
Views: 1742
Reputation: 1262
Based on the source for EventAssertsTests (replaced x
with _mqttBroker
):
[Fact]
public static void GotExpectedEvent()
{
var evt = Assert.RaisesAnyAsync<EventArgs>(
h => _mqttBroker.Started += h,
h => _mqttBroker.Started -= h,
() => Task.Run(() => _mqttBroker.StartAsync(new MqttServerOptions())));
Assert.NotNull(evt);
Assert.Equal(_mqttBroker, evt.Sender);
Assert.Equal(EventArgs.Empty, evt.Arguments);
}
Upvotes: 5