Iheuzio
Iheuzio
CC#
Created by Iheuzio on 4/19/2023 in #help
❔ Moq test exception thrown after adding and saved changes to the context object
For context it is stating that there is no previous command for add called to save the changes, however I added the user. Wondering why it isn't working here...
4 replies
CC#
Created by Iheuzio on 4/19/2023 in #help
❔ Moq test exception thrown after adding and saved changes to the context object
This is the adding method to the context object from the unit test
c#
// no issues with this code?
public bool addUser(User user){
if(user == null){
throw new ArgumentNullException("Cannot have null values");
}
try
{
// check to see if there is a user with the same username in db
User user_check = _context.Users.Where(u => u.Id == user.Id).FirstOrDefault();
if (user_check != null)
{
throw new Exception("User already exists");
}
// will add the user to the database + save changes to commit them.
_context.Users.Add(user);
_context.SaveChanges(); // gets added succesfully
return true;
}
catch (Exception e)
{
throw new Exception($"Failed to add user to database {e}");
}
}
c#
// no issues with this code?
public bool addUser(User user){
if(user == null){
throw new ArgumentNullException("Cannot have null values");
}
try
{
// check to see if there is a user with the same username in db
User user_check = _context.Users.Where(u => u.Id == user.Id).FirstOrDefault();
if (user_check != null)
{
throw new Exception("User already exists");
}
// will add the user to the database + save changes to commit them.
_context.Users.Add(user);
_context.SaveChanges(); // gets added succesfully
return true;
}
catch (Exception e)
{
throw new Exception($"Failed to add user to database {e}");
}
}
4 replies