首页 > 解决方案 > 为什么该方法不返回自定义异常消息

问题描述

我想要一个异步方法“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); 
}

标签: c#unit-testingmockingmoq

解决方案


您正在设置中实例化新对象,这些对象与您在调用 UpdateAsync 时实例化的对象不同,因此它们将不匹配并且 Mock 对象不会引发异常。如果传入正确类型的对象,您可以改为设置模拟以引发异常,同时 Url 参数也检查它是否具有 testUrl,例如:

rc.Setup(x => x.PutAsync(It.Is<Uri>(u => u.OriginalString == testUrl), It.IsAny<JObject>(), It.IsAny<NameValueCollection>())
    .ThrowsAsync(new Exception("TestMessage"));

推荐阅读