【发布时间】: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