简体   繁体   中英

ASP.Net.Core userManager.CreateAsync

When i debug the test than i see it goes trough the await userManager.CreateAsync(user) but then it goes to the catch where it should only go to if it is empty, wich it isn't. This is the controller:

public async Task<ActionResult<string>> CreateUser(UserVM userVM)
{
    ApplicationUser user = ModelConverter.ViewModelToModel.GetUser(userVM);

    var x =   await userManager.CreateAsync(user);

    List<ApplicationUser> users = userManager.Users.ToList();

    return user.Id;
}

This is one of the test i use:

 public void Should_AddShiftExchangeToUser()
 {
    MPContext context = CleanContext();
    UsersController usersController = new UsersController();
    try
    {
        var x = usersController.CreateUser(new ViewModels.UserVM()).Result;
        var y = usersController.CreateUser(new ViewModels.UserVM()).Result;
        var result = usersController.AddShiftExchange(new ShiftExchangeVM() { RequesterId = x.Value, ReceiverId = y.Value }, x.Value).Result;
        Assert.NotNull(result.Value);
        ShiftExchange shiftExchange = context.shiftExchanges.FirstOrDefaultAsync(s => s.Id == result.Value).Result;
        Assert.NotNull(shiftExchange);
        Assert.NotNull(shiftExchange.Receiver);
        Assert.NotNull(shiftExchange.Requester);
    }
    catch (Exception ex)
    {
        Assert.Null(ex);
    }
}

Then i get this error:

Message: Assert.Null() Failure Expected: (null) Actual: System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.) ---> 

the question i have is how do i go through the rest of the test, not that it goes to catch when i makes an user.

I am not sure what your function is attempting to do. You attempt to get the user, following which you attempt to create the user and then list all users before returning the id for the original get user request.

If the user does not exist initially then

ModelConverter.ViewModelToModel.GetUser(userVM)

will this return a null object when the user is not found or raise an exception? If it's the former, then

return user.Id;

will raise a null exception.

In addition, the create and list users lines do not seem to be relevant to the rest of the function as you do not utilise their responses for anything. Is this code sample the full copy of the function?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM