gpt4 book ai didi

c# - 测试异步/回调 Visual Studio

转载 作者:行者123 更新时间:2023-11-28 21:29:29 25 4
gpt4 key购买 nike

我需要为一大堆类似于以下示例的 C# 代码编写一些测试。这是我在 C# 中的第一个任务之一,我很不幸被直接转入异步代码:(。它是一个发出大量数据库请求的 Web 应用程序:

namespace Foo.ViewModel
{
public class FooViewModel
{
private ManagementService _managementService;
public int Status { get; set; }
public Foo()
{
Status = 5;
_managementService = new ManagementService();
_managementService.GetCustomerInfoCompleted += new EventHandler<GetCustomerInfoEventArgs>(CustomerInfoCallback);

}

public void GetCustomerInfo(int count)
{
int b;
if (someCondition() || otherCondition())
{
b = 2;
}
else
{
b = SomeOtherAsynchronousMethod();
}
_managementService.GetCustomerInfoAsync(b, count);
//when completed will call CustomerInfoCallback
}

void CustomerInfoCallback(object sender, GetCustomerInfoEventArgs args)
{
Status = args.Result.Result.Total;
UpdateView();
}

}

}

我希望能够像这样运行一个简单的测试:

    [TestMethod]
public void TestExecute5()
{
Foo f = new Foo();
f.GetCustomerInfo(5);
Assert.AreEqual(10, f.Status);
}

但显然使用异步方法并不是那么简单。

ManagementService 中可能有 40 个异步方法,由大约 15 个不同的 ViewModel 调用 - 这个 ViewModel 调用了大约 8 个异步方法。异步调用是通过基于事件的异步模式实现的,因此我们没有任何不错的“异步”或“等待”功能。

我该怎么做才能让测试以某种方式工作,以便我可以调用 GetCustomerInfo 方法并在回调完成后检查状态?

最佳答案

如果您要测试事件是否被触发,您需要一种进入事件处理程序的方法。由于您使用 integration-testsing 标记了您的问题,我假设您想测试服务和 View 模型是否正常协同工作。如果你允许依赖注入(inject)到你的 View 模型中,你可以这样构造:

public class ViewModel
{
private readonly ManagementService _managementService;
public ViewModel(ManagementService service)
{
_managementService = service;
}

public void DoSomething()
{
_managementService.DoWork();
}

}

public class ManagementService
{
public event EventHandler SomethingHappened;

public void DoWork()
{
System.Threading.Thread.Sleep(2000);
if (SomethingHappened != null)
SomethingHappened(this, null);
}
}

然后当你去测试你的 View 模型和服务时,你可以这样做:

[TestMethod, Timeout(5000)]
public void TestMethod1()
{
var testManagementService = new ManagementService();
AutoResetEvent evt = new AutoResetEvent(false);
testManagementService.SomethingHappened += delegate (System.Object o, System.EventArgs e)
{
evt.Set();
};

var vm = new ViewModel(testManagementService);
evt.WaitOne();
}

关于c# - 测试异步/回调 Visual Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28183435/

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