C#单元测试-无法从IHttpActionResult响应中提取内容
我有这个控制器C#单元测试-无法从IHttpActionResult响应中提取内容,c#,asp.net,unit-testing,asp.net-web-api,C#,Asp.net,Unit Testing,Asp.net Web Api,我有这个控制器 [Route("GeocacheAddressObjectList")] [HttpPost] public async Task<IHttpActionResult> GeocacheAddressObjectList([FromBody] List<GeocacheAddress> addresses) { //check valid addresses if(addresses == n
[Route("GeocacheAddressObjectList")]
[HttpPost]
public async Task<IHttpActionResult> GeocacheAddressObjectList([FromBody] List<GeocacheAddress> addresses)
{
//check valid addresses
if(addresses == null)
{
return BadRequest("Invalid addresses. The address list object is null!") as IHttpActionResult;
}
ElasticHelper searchHelper = new ElasticHelper(ConfigurationManager.AppSettings["ElasticSearchUri"]);
List<GeocacheAddress> geocodedAddresses = new List<GeocacheAddress>();
// check each address in the addresses list against geocache db
foreach (GeocacheAddress address in addresses)
{
var elasticSearchResult = SearchGeocacheIndex(address);
// found a match
if (elasticSearchResult.Total != 0)
{
SearchProperties standardizedAddressSearch = new SearchProperties();
standardizedAddressSearch.Size = 1;
standardizedAddressSearch.From = 0;
Address elasticSearchResultAddress = elasticSearchResult.Hits.ElementAt(0).Source;
// query the standardized key in geocache db
standardizedAddressSearch.ElasticAddressId = elasticSearchResultAddress.Standardized.ToString();
// the address is already standardized, return the standardized address with its geocode
if (standardizedAddressSearch.ElasticAddressId == "00000000-0000-0000-0000-000000000000")
{
geocodedAddresses.Add(new GeocacheAddress
{
Id = address.Id,
Street = elasticSearchResultAddress.AddressString,
City = elasticSearchResultAddress.City,
State = elasticSearchResultAddress.State,
ZipCode = elasticSearchResultAddress.Zipcode,
Plus4Code = elasticSearchResultAddress.Plus4Code,
Country = elasticSearchResultAddress.Country,
Latitude = elasticSearchResultAddress.Coordinates.Lat,
Longitude = elasticSearchResultAddress.Coordinates.Lon
});
}
else // perform another query using the standardized key
{
Address standardizedAddress = StandardAddressSearch(standardizedAddressSearch).Hits.ElementAt(0).Source;
if (standardizedAddress == null)
{
return BadRequest("No standardized address found in geocache database") as IHttpActionResult;
}
geocodedAddresses.Add(new GeocacheAddress()
{
Id = address.Id,
Street = standardizedAddress.AddressString,
City = standardizedAddress.City,
State = standardizedAddress.State,
ZipCode = standardizedAddress.Zipcode,
Plus4Code = standardizedAddress.Plus4Code,
Country = standardizedAddress.Country,
Latitude = standardizedAddress.Coordinates.Lat,
Longitude = standardizedAddress.Coordinates.Lon
});
}
}
else // not found in geocache db, call SmartStreets API
{
List<Address> address_list = new List<Address>();
using (HttpClient httpClient = new HttpClient())
{
//Send the request and get the response
httpClient.BaseAddress = new System.Uri(ConfigurationManager.AppSettings["GeocodingServiceUri"]);
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
//Lookup object to perform Geocoding service call
var postBody = JsonConvert.SerializeObject(new Lookup()
{
MaxCandidates = 1,
Street = address.Street,
City = address.City,
State = address.State,
ZipCode = address.ZipCode
});
var requestContent = new StringContent(postBody, Encoding.UTF8, "application/json");
// Send the request and get the response
var response = await httpClient.PostAsync("GeocodeAddressObject", requestContent);
if (!response.IsSuccessStatusCode) //error handling
{
geocodedAddresses.Add(new GeocacheAddress()
{
Id = address.Id,
Error = response.ReasonPhrase
});
}
Geocode geocodeFromGeocoder = JsonConvert.DeserializeObject<List<Geocode>>(response.Content.ReadAsStringAsync().Result).ElementAt(0);
GeocacheAddress geocodedAddress = new GeocacheAddress()
{
Id = address.Id,
Street = geocodeFromGeocoder.CorrectedAddress,
City = geocodeFromGeocoder.City,
State = geocodeFromGeocoder.State,
ZipCode = geocodeFromGeocoder.Zipcode,
Plus4Code = geocodeFromGeocoder.Plus4Code,
Country = geocodeFromGeocoder.Country,
Latitude = geocodeFromGeocoder.Latitude,
Longitude = geocodeFromGeocoder.Longitude
};
geocodedAddresses.Add(geocodedAddress);
// check each geocoded address against geocache db
Guid standardized_key;
var geocodedAddressResult = SearchGeocacheIndex(geocodedAddress);
// found a match
if (geocodedAddressResult.Total != 0)
{
Address standardizedAddress = geocodedAddressResult.Hits.ElementAt(0).Source;
standardized_key = standardizedAddress.AddressID;
}
else // not found, insert geocode into geocache db
{
Address new_standardized_address = createStandardizedAddress(geocodeFromGeocoder);
standardized_key = new_standardized_address.AddressID;
address_list.Add(new_standardized_address);
}
// insert non-standardized address into geocache db
Address new_nonstandardized_address = createNonStandardizedAddress(address, standardized_key);
address_list.Add(new_nonstandardized_address);
}
searchHelper.BulkIndex<Address>(address_list, "xxx", "xxx");
}
}
return Json(geocodedAddresses, new Newtonsoft.Json.JsonSerializerSettings()) as IHttpActionResult;
}
[路由(“GeocacheAddressObjectList”)]
[HttpPost]
公共异步任务GeocacheAddressObjectList([FromBody]列表地址)
{
//检查有效地址
如果(地址==null)
{
返回BadRequest(“无效地址。地址列表对象为空!”)作为IHttpActionResult;
}
ElasticHelper searchHelper=新的ElasticHelper(ConfigurationManager.AppSettings[“ElasticSearchUri]”);
List geocodedAddresses=新列表();
//对照geocache db检查地址列表中的每个地址
foreach(地址中的GeocacheAddress地址)
{
var elasticSearchResult=SearchGeocacheIndex(地址);
//找到一根火柴
如果(elasticSearchResult.Total!=0)
{
SearchProperties standardizedAddressSearch=新的SearchProperties();
标准化地址搜索。大小=1;
standardizedAddressSearch.From=0;
地址elasticSearchResultAddress=elasticSearchResult.Hits.ElementAt(0).Source;
//在geocache数据库中查询标准化密钥
standardizedAddressSearch.ElasticAddressId=elasticSearchResultAddress.Standardized.ToString();
//地址已标准化,请返回标准化地址及其地理代码
如果(standardizedAddressSearch.ElasticAddressId==“00000000-0000-0000-0000-0000-000000000000”)
{
GeoCodedAddress.Add(新的GeocacheAddress)
{
Id=地址。Id,
Street=elasticSearchResultAddress.AddressString,
城市=elasticSearchResultAddress.City,
状态=elasticSearchResultAddress.State,
ZipCode=elasticSearchResultAddress.ZipCode,
Plus4Code=elasticSearchResultAddress.Plus4Code,
国家=elasticSearchResultAddress.Country,
纬度=elasticSearchResultAddress.Coordinates.Lat,
经度=elasticSearchResultAddress.Coordinates.Lon
});
}
else//使用标准化键执行另一个查询
{
Address standardizedAddress=StandardAddressSearch(standardizedAddressSearch).Hits.ElementAt(0).Source;
if(标准化地址==null)
{
返回BadRequest(“在geocache数据库中找不到标准化地址”)作为IHttpActionResult;
}
添加(新的GeocacheAddress()
{
Id=地址。Id,
Street=标准化的Address.AddressString,
城市=标准化地址。城市,
State=标准化地址State,
ZipCode=标准化地址.ZipCode,
Plus4Code=标准化地址。Plus4Code,
国家=标准化地址。国家,
纬度=标准化地址.Coordinates.Lat,
经度=标准化地址.Coordinates.Lon
});
}
}
else//在geocache数据库中找不到,请调用SmartStreets API
{
列表地址_List=新列表();
使用(HttpClient HttpClient=new HttpClient())
{
//发送请求并获得响应
httpClient.BaseAddress=new System.Uri(ConfigurationManager.AppSettings[“GeocodingServiceUri]”);
httpClient.DefaultRequestHeaders.Accept.Add(新的System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(“应用程序/json”));
//查找对象以执行地理编码服务调用
var postBody=JsonConvert.SerializeObject(新查找()
{
MaxCandidates=1,
街道=地址。街道,
城市=地址。城市,
State=地址。State,
ZipCode=地址。ZipCode
});
var requestContent=newstringcontent(postBody,Encoding.UTF8,“application/json”);
//发送请求并获得响应
var response=wait httpClient.PostAsync(“GeocodeAddressObject”,requestContent);
if(!response.issucessStatusCode)//错误处理
{
添加(新的GeocacheAddress()
{
Id=地址。Id,
Error=response.ReasonPhrase
});
}
Geocode geocodeFromGeocoder=JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result).ElementAt(0);
GeocacheAddress geocodedAddress=新的GeocacheAddress()
{
Id=地址。Id,
街道=地理编码FromGeocoder.CorrectedAddress,
城市=地理编码fromGeocoder.City,
State=geocoderfromgeocoder.State,
ZipCode=geocodeFromGeocoder.ZipCode,
Plus4Code=geocodeFromGeocoder.Plus4Code,
国家=地理编码FromGeocoder.Country,
纬度=地理编码来自地理编码器。纬度,
经度=地理编码fromGeocoder.经度
};
geocodedAddress.Add(geocodedAddress);
//根据geocache db检查每个地理编码地址
桂
var result = await controller.GeocacheAddressObjectList(testGeocacheAddress) as OkNegotiatedContentResult<GeocacheAddress>;
[TestMethod]
public async Task TestMethod1()
{
var controller = new GeocachingController();
var testGeocacheAddress = new List<GeocacheAddress>();
testGeocacheAddress.Add(new GeocacheAddress
{
City = "Renton",
});
var result = await controller.GeocacheAddressObjectList(testGeocacheAddress);
var expected = GetGeocacheAddress();
Assert.AreEqual(result.Content.City, expected[0].City);
private List<GeocacheAddress> GetGeocacheAddress()
{
var testGeocacheAddress = new List<GeocacheAddress>();
testGeocacheAddress.Add(new GeocacheAddress
{
Id = Guid.Empty,
Street = "365 Renton Center Way SW",
City = "Renton",
State = "WA",
ZipCode = "98057",
Plus4Code = "2324",
Country = "USA",
Latitude = 47.47753,
Longitude = -122.21851,
Error = null
});
return testGeocacheAddress;
}
var result = await controller.GeocacheAddressObjectList(testGeocacheAddress) as JsonResult<List<GeocacheAddress>>;
public class FooController : ApiController
{
public IHttpActionResult Get()
{
var foo = "foo";
return Ok(foo);
}
}
[TestMethod]
public void Get_Foo_From_Controller()
{
var fooController = new FooController();
var result = fooController.Get();
//Here we are casting the expected type
var values = (OkNegotiatedContentResult<string>)result;
Assert.AreEqual("Foo", values.Content);
}