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);


 // ...


 }


}



...