C# · 12月 30, 2021

c# – 我如何模拟这个异步方法?

我有一个类似于这样的类: public class viewmodel{ public viewmodel(IWebService service) { this.WebService = service; } private IWebService WebService{get;set;} private IEnumerable<SomeData> MyData{get;set;} private void GetReferenceData() { this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete,null); } private void GetReferenceDataOnComplete(IAsyncResult result) { this.MyData = this.WebService.EndGetStaticReferenceData(result); } . . .}

我想嘲笑我的IWebService接口,以便在调用BeginGetStaticReferenceData时可以调用回调方法.我正在使用Moq,我无法解决如何做到这一点.我的单元测试设置代码看起来像:

//Arrangevar service = new Mock<IWebService>();service.Setup(x => x.BeginGetStaticReferenceData(/*…….don’t kNow…..*/));service.Setup(x => x.EndGetStaticReferenceData(It.IsAny<IAsyncResult>())).Returns(new List<SomeData>{new SomeData{Name=”blah”}});var viewmodel = new viewmodel(service.Object);..解决方法 就是这样: [TestMethod]public void Test10(){ var expectedData = new[]{new SomeData(),new SomeData()}; AsyncCallback callback = null; IAsyncResult ar = new Mock<IAsyncResult>().Object; var webServiceStub = new Mock<IWebService>(); webServiceStub .Setup(ws => ws.BeginGetStaticReferenceData(It.IsAny<AsyncCallback>(),null)) .Callback((AsyncCallback cb,object state) => callback = cb) .Returns(ar); webServiceStub .Setup(ws => ws.EndGetStaticReferenceData(It.IsAny<IAsyncResult>())) .Returns(expectedData); var sut = new viewmodel(webServiceStub.Object); sut.DoIt(); callback(ar); Assert.AreEqual(expectedData,sut.MyData);}

这个测试假定了一个稍微修改的viewmodel,我添加了几个公共成员来测试一些东西:

public class viewmodel{ public viewmodel(IWebService service) { this.WebService = service; } public IEnumerable<SomeData> MyData { get; set; } public void DoIt() { this.GetReferenceData(); } private IWebService WebService { get; set; } private void GetReferenceData() { this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete,null); } private void GetReferenceDataOnComplete(IAsyncResult result) { this.MyData = this.WebService.EndGetStaticReferenceData(result); }}