C# 单元测试 - 无法从 IHttpActionResult 响应中提取内容

Hus*_*ali 1 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 == 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;
    }
Run Code Online (Sandbox Code Playgroud)

我正在编写一个单元测试来测试这个控制器的某些部分。

我想将从控制器收到的响应与预期值进行比较。当我调试结果时,它会显示响应的内容,但我无法在代码中使用 (result.Content) 之类的内容。

当我尝试使用这一行时,它返回空响应。

        var result = await controller.GeocacheAddressObjectList(testGeocacheAddress) as OkNegotiatedContentResult<GeocacheAddress>;
Run Code Online (Sandbox Code Playgroud)

实际的单元测试代码。我将不胜感激任何帮助。

  [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);
Run Code Online (Sandbox Code Playgroud)

}

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;
    }
Run Code Online (Sandbox Code Playgroud)

Igo*_*gor 5

在您的单元测试中,您需要将结果转换为JsonResult<T>,更具体地说JsonResult<List<GeocacheAddress>>,这就是您要返回的内容。

var result = await controller.GeocacheAddressObjectList(testGeocacheAddress) as JsonResult<List<GeocacheAddress>>;
Run Code Online (Sandbox Code Playgroud)

如果你return Ok(geocodedAddresses)在你的控制器返回(你现在从那里返回调用Json)中使用,那么你可以转换为OkNegotiatedContentResult<List<GeocacheAddress>>.


同样在您的控制器代码中,您不需要将返回转换为,IHttpActionResult因为JsonResult<T>已经实现了。演员阵容是多余的。