【发布时间】:2019-02-04 21:34:58
【问题描述】:
我想要一个异步方法“UpdateAsync”在调用 PutAsync 方法时返回自定义异常消息。我现在要做的是模拟 PutAsync 所属的类,然后设置方法并提供参数。我还使用 Throws 来自定义异常消息。
问题是当我运行它时
var result = await this.repository.UpdateAsync(new EndPoint(new Uri(testUrl), HttpMethod.Put), JObject.FromObject(new object()), this.exceptionProcessor);
PutAsync 继续运行,没有返回异常。 这是代码。
Mock<RestClient> rc = new Mock<RestClient>();
rc.Setup(x => x.PutAsync(new Uri(testUrl), JObject.FromObject(new object()), new NameValueCollection()))
.Throws(new Exception("TestMessage"));
var result = await this.repository.UpdateAsync(new EndPoint(new Uri(testUrl), HttpMethod.Put), JObject.FromObject(new object()), this.exceptionProcessor);
Assert.IsTrue(result.ErrorMessages.GetValue(string.Empty).Equals("TestMessage"));
这里是UpdateAsync的主要部分,当进程到这里时,会先进入GetClient(),然后直接跳转到Exception。这个测试是用 Shimes 写的,但是我们不想再用 Shimes,所以我需要用另一种方式来做。
public virtual async Task<GenericOperationResult<object>> UpdateAsync(EndPoint endpoint, JContainer obj, IExceptionProcessor exceptionProcessor, NameValueCollection headers){
if (endpoint.ActionMethod == HttpMethod.Put)
{
result = await this.GetClient().PutAsync(endpoint.Url, obj, headers);
}
else if (endpoint.ActionMethod == HttpMethod.Post)
{
result = await this.GetClient().PostAsync(endpoint.Url, obj, headers);
}
else
{
throw new ConfigurationException("Update supports only POST or PUT verbs. Check endpoint configuration.");
}
return new GenericOperationResult<object>(200, result);
}
【问题讨论】:
-
当设置期望与实际传递给模拟方法的内容不匹配时,调用时它不会按预期运行。
-
您可能想要
.Returns(Task.FromException(new Exception("TestMessage")))而不是Throws。 -
@Lee 以你提供的方式显示无法将 Tasks.Task 转换为 Linq.JObject
标签: c# unit-testing mocking moq