c# - - - moq Test mock服务调用总是返回Null

时间:

首先寻址实现,避免混合异步等待和阻塞调用,如Wait().Result,这可能导致死锁,

引用异步Await Practices最佳在Asynchronous Programming中


public async Task<IList<T>> GetData<T>(string url) {


 try {


 var response = await client.GetAsync(url);


 var json = await response.Content.ReadAsStringAsync();


 var data = (JObject)JsonConvert.DeserializeObject(json);


 JArray arr = (JArray)data["resource"];


 return arr.ToObject<IList<T>>();


 } catch (InvalidCastException icEx) {


 throw new InvalidCastException("An error occurred when retrieving the data", icEx);


 }


 // Other catches


}



对于正在测试的主题方法,如果不需要等待,则无需使函数异步,只需返回Task


public Task<IList<MyObj>> GetActiveObjs() {


 return _myImplementedInterface.GetData<MyObj>(ActiveUrl);


}



现在对于测试来说,既然已经使用了任务,那么测试应该是异步的,subject 也在等待。


[Fact]


public async Task MyImplementedInterface_GetActive_ReturnsDataOrEmptyList() {


 using (var mock = AutoMock.GetLoose()) {


 //Arrange


 IList<MyObj> expected = _SomeStaticDataRepresentation;


 mock.Mock<IDataInterface>()


 .Setup(x => x.GetData<MyObj>(It.IsAny<string>()))


 .ReturnAsync(expected);



 var svc = mock.Create<MyService>();



 //Act


 var actual = await svc.GetActiveObjs();



 //Assert


 Assert.True(actual != null);


 Assert.True(actual == expected);


 // ...


 }


}



...