1

I'm new to C# and .NET, and when writing a test using SpecFlow, I get the error System.NullReferenceException: Object reference not set to an instance of an object. Apparently, when I try to access the "Response" in the other test methods the object is null, but I don't know why.

I searched here, and the questions I found (this one and this one) don't solve my problem.

My step file:

[Binding]
public sealed class UsersSteps
{
    private HttpResponseMessage Response { get; set; } = null!;
    private static readonly HttpClient Client = new HttpClient();

    [Given(@"I access the users route (.*)")]
    public async void GivenIAccessTheUsersRoute(string baseUrl)
    {
        var url = new Uri(baseUrl);
        Response = await Client.GetAsync(url);

        Console.WriteLine(">> Here it works: " + Response.StatusCode);
    }

    [Then(@"I should have only 1 registered user")]
    public void ThenIShouldHaveOnlyOneRegisteredUsers()
    {
        Console.WriteLine(">> Does not work here: " + Response.StatusCode);
    }

    [StepDefinition(@"should be admin")]
    public void AndShouldBeAdmin()
    {
        Console.WriteLine(">> Does not work here: " + Response.StatusCode);
    }

    [StepDefinition(@"your name should be Fulano da Silva")]
    public void AndYourNameShouldBeFulanoDaSilva()
    {
        Console.WriteLine(">> Does not work here: " + Response.StatusCode);
    }
}

My feature file:

Scenario: List users
    Given I access the users route https://serverest.dev/usuarios
    Then I should have only 1 registered users
    And should be admin
    And your name should be Fulano da Silva
  • 1
    Does this answer your question? [In SpecFlow how can I share data between steps/features?](https://stackoverflow.com/questions/2881685/in-specflow-how-can-i-share-data-between-steps-features) – gunr2171 Jul 27 '22 at 00:29
  • Thanks for trying to help @gunr2171, but that article didn't help me. – Lucas Dittrich Aug 12 '22 at 17:47

1 Answers1

4

Ahh, but did you check this one?

The key part is the comments:

Ensure that your method signature is async Task, not async void

[Given(@"I access the users route (.*)")]
public async Task GivenIAccessTheUsersRoute(string baseUrl)
//           ^^^^
Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
Andy Wynn
  • 1,171
  • 7
  • 11
  • Thanks, @Andrew Wynn! That was what was missing. As soon as I changed the **void** by **Task** the tests passed. – Lucas Dittrich Aug 12 '22 at 17:51
  • Just loose 3 hours looking for how my code can deadlock in xunit. Read every article I found and recode each testing class I used. I just love you @Andrew – siloob Aug 25 '22 at 14:27