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