本文介绍了使用NUnit和C#进行异步单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下创建的方法,花哨的只是从HTTP服务器检索数据,但这是一个异步方法.

I have the following method I created it's nothing fancy just retrieves data from an HTTP server but it is an async method.

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

然后在测试中,就像正常执行过程中一样,调用代码:

Then in the test I call the code just like I do during normal execution:

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

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

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

However I get an exception like so instead of any sort of string:

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#单元测试来说还很陌生.

I've looked around and found a few tutorials on this and tried it but to no avail. If anyone can point me in the right direction I would appreciate it, I'm pretty new to C# unit testing.

推荐答案

在Nunit Framework中,如下所示在单元测试中使用async/await:

In Nunit Framework, Use async/await in unit test as in the following:

[Test]
public async Task GetStringFromConsulTest()
{
    ConsulConfiguration cc = new ConsulConfiguration();
    //string a = cc.GetStringFromConsul("").GetAwaiter().GetResult();
    //use await instead

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

有关更多详细信息,请阅读异步支持NUnit

For more details, read Async Support in NUnit

最好在引发异常的情况下测试您的方法 NUnit预期异常

It's better to test your method in case of firing exceptions NUnit expected exceptions

更新:

评论:

该错误表示测试失败,并且源代码方法 GetStringFromConsul 中存在错误.

That error means that the test fail and there is a bug in the source code method GetStringFromConsul.

您的测试方法包括Assert语句:

Your test method include the Assert statement:

    Assert.AreEqual(a, "");

这意味着您希望通过 a = cc.GetStringFromConsul(")计算得出的 a 变量应为",否则,测试将失败,并且NUnit Framework会引发类似以下的异常:

That means that you expect a variable which is calculated from a=cc.GetStringFromConsul("") should be "" to pass,otherwise the test fail and NUnit Framework Fire an exception like:

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

要解决此异常,您应该解决方法 GetStringFromConsul 中的错误,当输入参数="

To resolve this exception, you should resolve the bug in the method GetStringFromConsul to return "" when the input parameter=""

这篇关于使用NUnit和C#进行异步单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:11