c# - 在 C# 方法中测试错误输入

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

因此,我正在尝试测试一种采用城市名称并通过输入虚假城市名称来调用 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);
                }
            }
        }

最佳答案

以防万一你还没有弄明白这是代码! 我还建议您看一下 async await 和 task,因为这些东西可能很复杂!

请注意 Task<string>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();
            }
        }
    }

关于c# - 在 C# 方法中测试错误输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54177688/

相关文章:

c# - 如何从 ASP.NET 按钮进行 HTTP POST?

unit-testing - Android Studio,assembleDebugTest导致多个dex文件定义

c# - 如何使用 SevenZipSharp 将文件添加到存档

c# - 使用 Async 避免重复代码

javascript - 使用 apply、call 或 bind 方法在 JavaScript 中进行依赖注入(inject)

unit-testing - 在两者都适用的情况下,端到端测试是否比单元测试更好?

testing - 使用控制台的分布式测试 - Jmeter

testing - Azure WebApp - 从 Kudu 控制台测试混合连接

javascript - Protractor - 如何从中继器而不是元素获取实际值?

c# - 如何使用反射创建或调用抽象类的 protected 构造函数?