最小起订量 Func<T1,任务的提高事件>



我有一个第三方类MqttClient,它里面有一个事件(Func<T1, Task>)。我想在MyClient类中监听这个事件,当它被调用时,我在类中更新属性IsConnected。对于我的测试,我模拟了IMqttClient接口,并且我想引发该事件,以便我可以测试我的属性在发生时得到更新。然而,当我尝试这样做时,我得到一个关于参数计数不匹配的错误。我发现了很多关于使用EventHandler<T>的例子,但由于这个类不在我的控制范围内,我需要它与Func一起工作。

System.Reflection。TargetParameterCountException: '参数计数不匹配。'

以下是我尝试过的测试:

[Fact]
public void Connect_IsConnectedSetToTrue()
{
MqttClientConnectedEventArgs eventArgs = new(new MqttClientConnectResult());
_mockMqttNetClient.Raise(x => x.ConnectedAsync += null);
_mqttClient.Connect();
Assert.True(_mqttClient.IsConnected);
}
[Fact]
public void Connect_IsConnectedSetToTrue()
{
MqttClientConnectedEventArgs eventArgs = new(new MqttClientConnectResult());
_mockMqttNetClient.Raise(x => x.ConnectedAsync += null, eventArgs);
_mqttClient.Connect();
Assert.True(_mqttClient.IsConnected);
}
[Fact]
public void Connect_IsConnectedSetToTrue()
{
MqttClientConnectedEventArgs eventArgs = new(new MqttClientConnectResult());
_mockMqttNetClient.Raise(x => x.ConnectedAsync += null, this, eventArgs);
_mqttClient.Connect();
Assert.True(_mqttClient.IsConnected);
}

MyClient类:

public class MyClient
{
private readonly IMqttClient _client;
public bool IsConnected { get; private set; } = false;
public MQTTClient(IMQTTNetClientFactory mqttNetFactory)
{
_client = mqttNetFactory.Create();
_client.ConnectedAsync += Client_ConnectedAsync;
}
public async Task Connect()
{
MqttClientOptions options = new MqttClientOptionsBuilder()
.WithTcpServer(_url, _port)
.WithCredentials(_username, _password)
.WithProtocolVersion(MqttProtocolVersion.V500)
.Build();
await _client.ConnectAsync(options);
}

private Task Client_ConnectedAsync(MqttClientConnectedEventArgs arg)
{
_logger.LogInformation("Client connected to the MQTT broker.");
IsConnected = true;
return Task.FromResult(0);
}
}

这是MqttClient类内部的事件。

public interface IMqttClient : IDisposable
{
event Func<MqttClientConnectedEventArgs, Task> ConnectedAsync;
}

谢谢,亚当

正如@Ralf所说

当只给定一个args类时,你使用的raise重载期望它是一个eventandler (sender+args之类的东西),并将发送方插入调用

这样做解决了我的问题。

_mockMqttNetClient.Raise(x => x.DisconnectedAsync += null, new object[] { eventArgs });

相关内容

  • 没有找到相关文章

最新更新