gpt4 book ai didi

c# - 我如何使用 xUnit Assert.RaisesAny?

转载 作者:行者123 更新时间:2023-12-04 02:52:58 25 4
gpt4 key购买 nike

如何使用 xUnit Assert.RaisesAny()?我似乎找不到任何示例。

我收到以下语法错误

The event 'IMqttServer.Started' can only appear on the left hand side of += or -=

这是有道理的,因为我没有订阅它,但我不知道 RaisesAny() 使用什么语法

基本上,我只是想检查 Broker 是否已启动,至少有 1 个客户端连接到它并且它已停止。

附言MqttServer 是一个 Mqtt Broker 实现,它是 MqttNet 的一部分

这是我的测试

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);
}
}
}

最佳答案

基于 the source for EventAssertsTests (将 x 替换为 _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);
}

关于c# - 我如何使用 xUnit Assert.RaisesAny?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54129202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com