【问题标题】:Testing false input in a C# method在 C# 方法中测试错误输入
【发布时间】:2019-06-08 05:10:17
【问题描述】:

所以我正在尝试测试一种方法,该方法采用城市名称并通过输入假城市名称来调用 OpenWeatherMap Web API,但我完全不知道如何做到这一点,因为到目前为止我遇到的所有示例都有一直在测试类而不是方法。

如何将假城市名称传递给该方法?另外,调用 API 的方法返回一个任务,那么我该如何检查输出字符串?

我对测试领域完全陌生,因此非常感谢任何帮助。我还在这里包含了我的方法代码。

    static void Main()
    {
        string output;

        //Declare variables
        string strUserLocation;

        //Prompt user for city name
        Console.Write("Enter your city name: ");
        strUserLocation = Console.ReadLine();

        try
        {
            //Retrieve data from API
            Task<string> callTask = Task.Run(() => CallWebAPI(strUserLocation));
            callTask.Wait();

            //Get the result
            output = callTask.Result;
            Console.WriteLine(output);

            if(output == "Invalid city name. \n")
            {
                Main();
            }

            else
            {
                //Quit application
                Console.WriteLine("Press the ENTER key to quit the application.");
                Console.ReadLine();
            }
        }

        catch (Exception)
        {
            Console.WriteLine("Invalid city name. \n");
            Main();
        }
    }//end Main


    //Method to call OpenWeatherMap API
    static async Task<string> CallWebAPI(string location)
    {
        using (HttpClient client = new HttpClient())
        {
            //Set base URI for HTTP requests
            client.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5/weather"); 

            //Tells server to send data in JSON format
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string strLocation = location;
            string strKey = "keyplaceholder123";

            //Send request and await response from server
            HttpResponseMessage response = await client.GetAsync("?q=" + strLocation + "&APPID=" + strKey);

            if(response.StatusCode == HttpStatusCode.OK)
            {
                CurrentWeather weather = response.Content.ReadAsAsync<CurrentWeather>().Result;

                //Convert temperature from Kelvin to Fahrenheit
                float temp = weather.main.temp * 1.8f - 459.67f;
                string strTempFahrenheit = temp.ToString("n0");

                //Display output
                return "The temperature in " + weather.name + " is " + strTempFahrenheit + "°F. \n";
            }

            else
            {
                return "Invalid city name. \n";
            }
        }//end using
    }//end CallWebAPI

目前为止的测试

    using System;
    using TechnicalExercise;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    namespace TechnicalExercise.Test
    {
        [TestClass]
        public class InputTest
        {
                [TestMethod]
                public void UserInput_EnterFakeCity_ReturnError()
                {
                    //Arrange
                    string strFakeCity = "Fake Lake City";
                    string expected = "Invalid city name. \n";
                    string actual;

                    //Act - Retrieve data from API
                    Task<string> callTask = Task.Run(() => CallWebAPI(strFakeCity));
                    callTask.Wait();
                    actual = callTask.Result;

                    //Assert - Checks if the actual result is as expected
                    Assert.Equals(actual, expected);
                }
            }
        }

【问题讨论】:

  • 所有语言的测试都是一样的。如果你想测试输出 return 输出。不要将其写入控制台
  • 城市名不是location吗?然后它被传递给client.GetAsync(在将它分配给另一个名为strLocation的字符串之后,出于某种原因)?另外,你指的是void是哪个方法?
  • @RufusL 是的,位置是城市名称,抱歉,我刚刚意识到该方法不是无效的,而是返回一个任务,但我想检查的是输出变量。我不知道如何将假城市名称传递给该方法并检查它是否返回正确的输出字符串。
  • 在此处发布您的strKey 可能违反openweathermap.org 的条款和条件。

标签: c# unit-testing testing asp.net-web-api


【解决方案1】:

以防万一你还没弄明白这里是代码! 我还建议您看一下异步等待和任务,因为这些事情可能很复杂!

请注意Task&lt;string&gt;returns 而不是output =

    static async Task<string> CallWebAPI(string location)
    {
        //string output;

        using (HttpClient client = new HttpClient())
        {
            //Set base URI for HTTP requests
            client.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5/weather");

            //Tells server to send data in JSON format
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string strLocation = location;
            string strKey = "427hdh9723797rg87";

            //Send request and await response from server
            HttpResponseMessage response = await client.GetAsync("?q=" + strLocation + "&APPID=" + strKey);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                CurrentWeather weather = response.Content.ReadAsAsync<CurrentWeather>().Result;

                //Convert temperature from Kelvin to Fahrenheit
                float temp = weather.main.temp * 1.8f - 459.67f;
                string strTempFahrenheit = temp.ToString("n0");

                //Display output
                return "The temperature in " + weather.name + " is " + strTempFahrenheit + "°F. \n";
            }

            else
            {
                return "Invalid city name. \n";
                //Console.WriteLine(output);
                Main();
            }
        }
    }

【讨论】:

  • 感谢这确实有助于解决我的 void Task 方法问题!我现在已经把我的代码改成了这个。
  • 我仍然无法弄清楚如何将参数传递给方法,而不是实例化一个类并对其进行测试,所以如果你能提供任何建议,我将非常感激!跨度>
  • 欢迎您:P,如果您的意思是任务,我建议您一路异步。我的意思是,例如,如果您有一个 ui 和后端,您将不会在同一个线程中运行它,因为 ui 会卡住,因为您将在后端等待线程结果。线程可以这样调用 var result = await CallWebApi(location);但是等待出现的函数必须是异步方法,因为它必须等待某些东西。如果它解决了您的问题,请选择我的答案作为答案。它可能会帮助其他人:P
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 2019-05-11
相关资源
最近更新 更多