S
S
stcmd042362017-07-06 13:09:39
ASP.NET
stcmd04236, 2017-07-06 13:09:39

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

It is when the class is created that the error is thrown. But inside there is nothing except assigning a value. Nothing is set in the constructor either.
And this is a test
[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);
        }
    }

I suspect that there is something wrong with my test. I'm not writing the test correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maronus, 2017-07-10
@Maronus

Try adding the FromBody attribute

public async Task<IHttpActionResult> Register([FromBody] RegisterBindingModel model)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question