gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:02 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com