下面是我进行 API 调用的代码,并且我从 API 调用(Satus:200)成功获得了结果。我想为相同的场景添加一个 Unite 测试用例,但是我看到 API 调用在我的 Unit 测试用例中失败,它返回 503 服务器不可用或httpWebRequest.GetRequestStream()
在代码中调用 ( ) 时超时。但是同样的 API 调用在我的主应用程序中运行良好,N + 次成功,下面是代码
public string FetchToken()
{
string output = string.Empty;
var method = MethodBase.GetCurrentMethod();
var cep = ConfigurationManager.AppSettings["TokenAPI"].ToString();
var suser = ConfigurationManager.AppSettings["usr"].ToString();
var httpWebRequest = (HttpWebRequest)WebRequest.Create(Path.Combine(cep, suser));
httpWebRequest.Headers.Add("X-nSpace", ConfigurationManager.AppSettings["nSpace"].ToString());
httpWebRequest.ContentType = "application/json";
httpWebRequest.KeepAlive = true;
httpWebRequest.Accept = "*/*";
httpWebRequest.Host = ConfigurationManager.AppSettings["HostKey"].ToString();
httpWebRequest.Method = "POST";
string json = string.Empty;
try
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var cDtls = new Dictionary<string, string>();
var cK = ConfigurationManager.AppSettings["cKey"].ToString();
var cId = ConfigurationManager.AppSettings["cID"].ToString();
cDtls.Add(cK, cId);
json = JsonConvert.SerializeObject(cDtls);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var parse = JObject.Parse(streamReader.ReadToEnd());
var authObject = parse["attr"];
output = authObject["ct_k"].ToString();
}
}
catch (Exception ex)
{
output = string.Empty;
}
return output;
}
我的单元测试用例方法
[TestMethod]
public void FetchToken_Pass_Test()
{
using (ShimsContext.Create())
{
IFetchService service = new FetchService();
var fetchInput = new FetchInputPC();
var fetchService = new FetchServicePC();
fetchInput.FetchInput = "3af5fd9c309f47d489895a8b352fca9d987";
var fetchOutput = fetchService.FetchToken(fetchInput);
Assert.AreEqual(fetchOutput.FetchValue, "ivK%2FngulI%2BzImce9R7%2BbaptVBX82fg%2FHaWoPke3%2Bp03Yw6hQfJ17REfuj%2Bv02XAlfxbNKALYKymVc%3D");
}
}
该FetchToken
方法在我的主应用程序中运行良好,它仅在单元测试用例中引起问题我已经检查了所有必要的 API 端点,并且应用程序和单元测试用例配置的凭据都已到位,并且相同。