Google 지오 코드 API에 Specflow를 구현하려고하지만 반복적으로 나타납니다. System.NullReferenceException : 개체 참조가 개체 인스턴스로 설정되지 않았습니다. 및 RootObject는 항상 null로 설정됩니다. 누군가 나를 도울 수 있습니까? 아래 내 단계 정의C# Specflow 개체 참조가 개체의 인스턴스로 설정되지 않았습니다.
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; }
}
}
결과 스택 트레이스 :
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.
"이 코드를 실행할 때마다"root "개체가"null "로 설정되어 있지만"root = JsonConvert.DeserializeObject (response); "가 실행될 때 아무런 오류가없는 것은 사용자가 의미하는 바가 무엇인지 분명하지 않습니다." - 스택 트레이스를 제공해 줄 수 있겠 니? 우리는 예외가 던져지고있는 곳을 알 수 없습니다. 어떤 진단도 도움이 될 것입니다 ... –
[NullReferenceException은 무엇이며 어떻게 수정합니까?] (http://stackoverflow.com/questions/4660142/what-is-a) -nullreferenceexception-and-how-do-i-fix-it) – HimBromBeere
"결과"개체는 어떻게 생겼습니까? 더 중요하게도 json의 결과와 일치합니다. 더 이상 직렬화가 발생하지 않는 것 같습니다. – Darren