2016-09-26 56 views
0

我試圖爲Google地理代碼API實現Specflow,但是我反覆獲取System.NullReferenceException:未將對象引用設置爲對象的實例。和RootObject始終設置爲空。有人能幫助我嗎?下面 是我的步驟定義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. 
+0

我不清楚你的意思是什麼,並且當我運行這段代碼時,對象「root」被設置爲null,但是在執行「root = JsonConvert.DeserializeObject(response);」這一行時沒有錯誤。 - 你能提供堆棧跟蹤嗎?我們無法確定拋出異常的位置。你所得到的任何診斷信息也會有所幫助...... –

+0

[可能是NullReferenceException異常,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a -nullreferenceexception-and-how-do-i-fix-it) – HimBromBeere

+1

你的「結果」對象是什麼樣子的;更重要的是,它是否與json中的結果相匹配 - 似乎更多的情況是反序列化沒有發生。 – Darren

回答

0

你的問題很可能是你們已經做出了一步async時,這是不specflow支持,所以你的方法

public async Task WhenTheClientGetsResponseBy(string addr)

可能是返回在這條線:

var response = await cl.GetStringAsync(uri); 

specflow不在任務中等待,所以它繼續下一步,然後你的root.results[0]沒有設置任何東西,所以空引用異常

1

山姆持有人,你是對的,

我改變了代碼:

var response = await cl.GetStringAsync(uri); 

要:

response = cl.GetStringAsync(uri).Result; 

這解決了我的問題。

相關問題