- 我有一个来自BackgroundService的类实现,我想编写xunit测试ExecuteAsync函数。每个人都有这个问题或对xunit for BackgroundService有所了解,请帮助我。
我正在使用IServiceCollection并启动它。但这在我调用API时就停止了。
- 代码
public class MakeCommandMqtt : BackgroundService
{
private readonly ILogger<MakeCommandMqtt> _logger;
private static IManagedMqttClient client;
public MakeCommandMqtt(ILogger<MakeCommandMqtt> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Brokerへ接続
await ConnectAsync();
// Subscribe
await SubscribeAsync("/MakeCommand");
// メッセージをハンドル
client.UseApplicationMessageReceivedHandler(async e =>
{
MakeCommandRequestJson makeCommandReq = new MakeCommandRequestJson();
MakeCommandResponseJson makeCommandRes = new MakeCommandResponseJson();
string topic = e.ApplicationMessage.Topic;
try
{
if (string.IsNullOrWhiteSpace(topic) == false)
{
string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
makeCommandReq = Newtonsoft.Json.JsonConvert.DeserializeObject<MakeCommandRequestJson>(payload);
makeCommandRes = registerMakeCommand(makeCommandReq);
}
}
catch (Exception ex)
{
_logger.LogWarning(ex.Message);
_logger.LogWarning(ex.StackTrace);
makeCommandRes.status = -1;
}
if (makeCommandRes.status == -1)
{
return;
}
makeCommandReq.servercommand["selecttime"] = DateTime.Now.ToString("yyyyMMddHHmmss");
await PublishAsync("/" + makeCommandReq.common.imei + "/MakeCommand", Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(makeCommandReq)), false, 1);
});
}