Answer the question
In order to leave comments, you need to log in
Why is a NullReferenceException thrown when an object is created?
Good afternoon! I am writing a test for the AccountController controller which is generated when the project is created. When I run the project and manually transfer the data, it works without errors. But during integration testing, it throws an error on null when the ApplicationUser class is created.
Here is the method that creates the user
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
// вот здесь выдается ошибка на null
var user = new ApplicationUser()
{
UserName = model.Email,
Email = model.Email,
PhoneNumber = string.IsNullOrEmpty(model.PhoneNumber) ? string.Empty : model.PhoneNumber
};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
return GetErrorResult(result);
if (model.OwnerId.HasValue)
{
if (!model.OwnerId.Value.Equals(User.Identity.GetUserId<int>()))
return Unauthorized();
await UserManager.AddToRoleAsync(user.Id, "user");
}
else
await UserManager.AddToRoleAsync(user.Id, "admin");
return Ok();
}
[TestClass]
public class AccountControllerTest
{
protected TestServer Server;
[TestInitialize]
public void Setup()
{
Server = TestServer.Create(app =>
{
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
});
}
[TestCleanup]
public void TestDispose()
{
if(Server != null)
Server.Dispose();
}
[TestMethod]
public async Task Register()
{
var registerBindingModel = new RegisterBindingModel()
{
PhoneNumber = "+71231234567",
Password = "Example_123456",
ConfirmPassword = "Example_123456",
Email = "[email protected]"
};
string jsonContent = JsonConvert.SerializeObject(registerBindingModel);
var response = await Server.HttpClient.PostAsync("api/Account/Register", new StringContent(jsonContent, Encoding.UTF8, "application/json"));
var result = response.Content.ReadAsStringAsync().Result;
Console.Out.WriteLine("Http operation unsuccesfull");
Console.Out.WriteLine($"Status : {response.StatusCode}");
Console.Out.WriteLine($"Reason : {response.ReasonPhrase}");
Console.Out.WriteLine($"Content: {result}");
Console.Out.WriteLine(response);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, result);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question