在C#方法中测试错误输入
因此,我试图测试一个方法,该方法采用城市名称,并通过输入假城市名称来调用OpenWeatherMapWebAPI,但我完全不知道如何做到这一点,因为到目前为止,我遇到的所有示例都是测试类而不是方法 我如何向该方法传递假城市名称?另外,调用API的方法返回一个任务,那么如何检查输出字符串呢 我是测试领域的新手,因此非常感谢您的帮助。我还包括了我的方法代码在C#方法中测试错误输入,c#,unit-testing,testing,asp.net-web-api,C#,Unit Testing,Testing,Asp.net Web Api,因此,我试图测试一个方法,该方法采用城市名称,并通过输入假城市名称来调用OpenWeatherMapWebAPI,但我完全不知道如何做到这一点,因为到目前为止,我遇到的所有示例都是测试类而不是方法 我如何向该方法传递假城市名称?另外,调用API的方法返回一个任务,那么如何检查输出字符串呢 我是测试领域的新手,因此非常感谢您的帮助。我还包括了我的方法代码 static void Main() { string output; //Declare v
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
static void Main()
{
字符串输出;
//声明变量
字符串结构定位;
//提示用户输入城市名称
控制台。写下(“输入您的城市名称:”);
strUserLocation=Console.ReadLine();
尝试
{
//从API检索数据
Task callTask=Task.Run(()=>CallWebAPI(strUserLocation));
callTask.Wait();
//得到结果
输出=callTask.Result;
控制台写入线(输出);
如果(输出=“无效的城市名称。\n”)
{
Main();
}
其他的
{
//退出申请
WriteLine(“按ENTER键退出应用程序”);
Console.ReadLine();
}
}
捕获(例外)
{
Console.WriteLine(“无效的城市名称。\n”);
Main();
}
}//端干管
//方法调用OpenWeatherMapAPI
静态异步任务CallWebAPI(字符串位置)
{
使用(HttpClient=new HttpClient())
{
//为HTTP请求设置基本URI
client.BaseAddress=新Uri(“http://api.openweathermap.org/data/2.5/weather");
//告诉服务器以JSON格式发送数据
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
字符串strLocation=位置;
字符串strKey=“KeyPlaceholder 123”;
//发送请求并等待服务器的响应
HttpResponseMessage response=wait client.GetAsync(“?q=“+strLocation+”&APPID=“+strKey”);
if(response.StatusCode==HttpStatusCode.OK)
{
CurrentWeather weather=response.Content.ReadAsAsync().Result;
//将温度从开尔文转换为华氏度
浮子温度=weather.main.temp*1.8f-459.67f;
字符串strTempFahrenheit=字符串的温度(“n0”);
//显示输出
返回“+weather.name+”中的温度为“+strtempfhrenheit+”°F.\n”;
}
其他的
{
返回“无效的城市名称。\n”;
}
}//终端使用
}//结束调用WebAPI
我到目前为止所做的测试
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);
}
}
}
使用系统;
运用技术技能;
使用Microsoft.VisualStudio.TestTools.UnitTesting;
名称空间TechnicalExercise.Test
{
[测试类]
公共类输入测试
{
[测试方法]
public void UserInput\u EnterFakeCity\u ReturnError()
{
//安排
字符串strFakeCity=“假湖城”;
字符串应为=“无效的城市名称。\n”;
字符串实际值;
//Act-从API检索数据
Task callTask=Task.Run(()=>CallWebAPI(strFakeCity));
callTask.Wait();
实际=callTask.Result;
//断言-检查实际结果是否与预期一致
Assert.Equals(实际、预期);
}
}
}
以防万一你还没弄明白,这是代码!
我还建议您了解异步等待和任务,因为这些事情可能很复杂
请注意任务
和返回
,而不是输出=
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();
}
}
}
静态异步任务CallWebAPI(字符串位置)
{
//字符串输出;
使用(HttpClient=new HttpClient())
{
//为HTTP请求设置基本URI
client.BaseAddress=新Uri(“http://api.openweathermap.org/data/2.5/weather");
//告诉服务器以JSON格式发送数据
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
字符串strLocation=位置;
字符串strKey=“427hdh9723797rg87”;
//发送请求并等待服务器的响应
HttpResponseMessage response=wait client.GetAsync(“?q=“+strLocation+”&APPID=“+strKey”);
if(response.StatusCode==HttpStatusCode.OK)
{
CurrentWeather weather=response.Content.ReadAsAsync().Result;
//将温度从开尔文转换为华氏度
浮子温度=weather.main.temp*1.8f-459.67f;
字符串strTempFahrenheit=字符串的温度(“n0”);
//显示输出
返回“+weather.name+”中的温度为“+strtempfhrenheit+”°F.\n”;
}
其他的
{
返回“无效的城市名称。\n”;
//控制台写入线(输出);
Main();
}
}
}
所有语言的测试都是相同的。如果要测试输出,请返回输出。不要将其写入控制台城市名称不是位置
?然后它被传递到client.GetAsync
(出于某种原因,在将它分配给另一个名为strLocation
的字符串之后)?另外,您所指的是void
@