c# - 使用 NUnit 和 C# 进行异步单元测试

标签 c# asynchronous nunit

我创建了以下方法,它只是从 HTTP 服务器检索数据没什么特别的,但它是一个异步方法。

public async Task<string> GetStringFromConsul(string key)
    {
        string s = "";

        // attempts to get a string from Consul
        try
        {
            //async method to get the response
            HttpResponseMessage response = await this.http.GetAsync(apiPrefix + key);

            //if it responds successfully
            if (response.IsSuccessStatusCode)
            {
                //parse out a string and decode said string
                s = await response.Content.ReadAsStringAsync();
                var obj = JsonConvert.DeserializeObject<List<consulValue>>(s);
                s = Encoding.UTF8.GetString(Convert.FromBase64String(obj[0].value));
            }
            else
            {
                s = requestErrorCodePrefix + response.StatusCode + ">";
            }
        } 
        catch(Exception e)
        {
            //need to do something with the exception
            s = requestExceptionPrefix + e.ToString() + ">";
        }

        return s;
    }

然后在测试中我像正常执行时一样调用代码:

[Test]
    public async Task GetStringFromConsulTest()
    {
        ConsulConfiguration cc = new ConsulConfiguration();

        string a = cc.GetStringFromConsul("").GetAwaiter().GetResult();
        Assert.AreEqual(a, "");
    }

但是我得到了这样的异常,而不是任何类型的字符串:

Message:   Expected string length 514 but was 0. Strings differ at index 0.
  Expected: "<Request Exception: System.Threading.Tasks.TaskCanceledExcept..."
  But was:  <string.Empty>

我环顾四周,找到了一些关于此的教程并尝试了但无济于事。如果有人能指出我正确的方向,我将不胜感激,我是 C# 单元测试的新手。

最佳答案

我是一个很好的错误消息的坚持者,所以我首先将断言更改为

Assert.AreEqual("", a);

因为第一个 参数是您的期望值。现在它将失败

Message:   Expected string length 0 but was 514. Strings differ at index 0.
  Expected:  <string.Empty>
   But was: "<Request Exception: System.Threading.Tasks.TaskCanceledExcept..."

...仍然是一个失败,但一个更明智的消息。

接下来,按照 M Hassan 的建议,为您的异步方法调用添加一个 await。

关于c# - 使用 NUnit 和 C# 进行异步单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49338398/

相关文章:

c# - asp.net c# 分配字符串的奇怪问题

c# - 使用 async-await 进行数据库查询

angularjs - 加载完成后触发回调

c# - 如何防止 resharper 8 使用 nunit 运行并行测试?

c# - 覆盖 azure 应用服务应用程序设置中的数组

c# - IList-LINQ进行过滤和排序

c# - 在 GROUP BY MySQL 查询上读取 IDataReader

java - 从 Firebase (android) 获取数据时如何避免代码重复?

c# - 使用 Moq 是否毫无意义,因为 Returns() 重新定义了您的方法的行为?

c# - NUnit 的奇怪行为,ExpectedException & yield return