c# Specflow对象引用未设置为对象的实例

本文关键字:对象 实例 设置 Specflow 对象引用 | 更新日期: 2023-09-27 18:08:46

我正试图实现Specflow的谷歌地理代码api,但我反复得到系统。NullReferenceException:对象引用没有设置为对象的实例。和RootObject总是被设置为null。有人能帮帮我吗?下面是我的Step定义

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; }
}
}

Result 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.

c# Specflow对象引用未设置为对象的实例

您的问题很可能是您已经使您的步骤async时,这是不支持specflow,所以您的方法

public async Task WhenTheClientGetsResponseBy(string addr)

可能在这行返回:

var response = await cl.GetStringAsync(uri);

和specflow不是在等待任务,所以它然后继续到下一步,然后你的root.results[0]不设置为任何东西,所以空引用异常

Sam Holder,你是对的,

我更改了代码:

var response = await cl.GetStringAsync(uri);

:

response = cl.GetStringAsync(uri).Result;

我的问题解决了