我正在尝试为Google地理代码API实现Specflow,但是我反复得到 System.NullReferenceException:对象引用未设置为对象的实例。并且RootObject始终设置为null。有人能帮助我吗? 下面是我的步骤定义
namespace NUnit.Tests1.StepDefinition
{
[Binding]
public sealed class GoogleSteps
{
private string googleapiurl;
private RootObject root = new RootObject();
[Given(@"Google api that takes address and returns latitude and longitude")]
public void GivenGoogleApiThatTakesAddressAndReturnsLatitudeAndLongitude()
{
googleapiurl = "http://maps.googleapis.com/maps/api/geocode/json?address=";
}
[When(@"The client Gets response by ""(.*)""")]
public async Task WhenTheClientGetsResponseBy(string addr)
{
HttpClient cl = new HttpClient();
StringBuilder sb = new StringBuilder();
sb.Append(googleapiurl);
sb.Append(addr);
Uri uri = new Uri(sb.ToString());
var response = await cl.GetStringAsync(uri);
root = JsonConvert.DeserializeObject<RootObject>(response);
}
[Then(@"The ""(.*)"" and ""(.*)"" returned should be as expected")]
public void ThenTheAndReturnedShouldBeAsExpected(string exp_lat, string exp_lng)
{
var location = root.results[0].geometry.location;
var latitude = location.lat;
var longitude = location.lng;
Console.WriteLine("Testing upali");
Console.WriteLine("location: lat " + location.lat);
Console.WriteLine("location: long " + location.lng);
Assert.AreEqual(location.lat.ToString(), exp_lat);
Assert.AreEqual(location.lng.ToString(), exp_lng);
}
}
}
Json的回应是:
{
"results": [
{
"address_components": [
{
"long_name": "1600",
"short_name": "1600",
"types": [
"street_number"
]
},
{
"long_name": "Amphitheatre Parkway",
"short_name": "Amphitheatre Pkwy",
"types": [
"route"
]
},
{
"long_name": "Mountain View",
"short_name": "Mountain View",
"types": [
"locality",
"political"
]
},
{
"long_name": "Santa Clara County",
"short_name": "Santa Clara County",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "California",
"short_name": "CA",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
},
{
"long_name": "94043",
"short_name": "94043",
"types": [
"postal_code"
]
}
],
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry": {
"location": {
"lat": 37.4223329,
"lng": -122.0844192
},
"location_type": "ROOFTOP",
"viewport": {
"northeast": {
"lat": 37.4236818802915,
"lng": -122.0830702197085
},
"southwest": {
"lat": 37.4209839197085,
"lng": -122.0857681802915
}
}
},
"place_id": "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types": [
"street_address"
]
}
],
"status": "OK"
}
我的RootObject类如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NUnit.Tests1.GoogleAPI
{
public class RootObject
{
public List<Result> results { get; set; }
public string status { get; set; }
}
}
结果StackTrace:
Test Name: VerifyLatitudeAndLongitude
Test FullName: NUnit.Tests1.FeatureFiles.GoogleGeoCodeFeature.VerifyLatitudeAndLongitude
Test Source: C:\Users\nandyu\documents\visual studio
2015\Projects\NUnit.Tests1\NUnit.Tests1\FeatureFiles\GoogleGeoCode.feature :
line 5
Test Outcome: Failed
Test Duration: 0:00:00.069
Result StackTrace:
at
NUnit.Tests1.StepDefinition.GoogleSteps.ThenTheAndReturnedShouldBeAsExpected(String exp_lat, String exp_lng) in C:\Users\nandyu\documents\visual studio 2015\Projects\NUnit.Tests1\NUnit.Tests1\StepDefinition\GoogleSteps.cs:line 42
at lambda_method(Closure , IContextManager , String , String )
at TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding binding,
IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch match, Object[] arguments)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(StepInstance stepInstance)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
at TechTalk.SpecFlow.TestRunner.CollectScenarioErrors()
at NUnit.Tests1.FeatureFiles.GoogleGeoCodeFeature.ScenarioCleanup()
at
NUnit.Tests1.FeatureFiles.GoogleGeoCodeFeature.VerifyLatitudeAndLongitude()
in C:\Users\nandyu\documents\visual studio
2015\Projects\NUnit.Tests1\NUnit.Tests1\FeatureFiles\GoogleGeoCode.feature:line 8
Result Message: System.NullReferenceException : Object reference not set to an instance of an object.
答案 0 :(得分:1)
Sam Holder,你是对的,
我更改了代码:
var response = await cl.GetStringAsync(uri);
要:
response = cl.GetStringAsync(uri).Result;
这解决了我的问题。
答案 1 :(得分:0)
如果specflow不支持您的步骤async
,那么您的问题很可能已解决,因此您的方法
public async Task WhenTheClientGetsResponseBy(string addr)
可能会回到这一行:
var response = await cl.GetStringAsync(uri);
并且specflow没有等待任务,所以它继续下一步然后你的root.results[0]
没有设置为任何东西,所以null引用异常