I have an ASP.NET MVC project and I write my service according to this:
public class UserService : IUserService { public void AddUser(UserModel userModel) { if (ModelState.IsValid){ var user = new User { FirstName = userModel.FirstName, LastName = userModel.LastName, Email = userModel.Email, Age = userModel.Age }; using (var context = new MyDbContext()) { context.Users.Add(user); } } }
And my DbContext class:
public class MyDbContext : DbContext { public MyDbContext(): base("name=mydb"){} public DbSet<User> Users {get; set;}
This works fine for the most part, but the problem arises when I want to try testing it. I follow the general recommendations here with bullying, but this is only if the DbContext is declared as an instance of the class, as opposed to a function variable. I want to do it like this because it allows me to control the transaction and the deletion of the context. Anyone have any suggestions on how to do this?
My bullying is as follows:
public class UserServiceTest { [Fact] public void TestAddUser() { var userSet = GetQueryableMockDbSet(userData.ToArray()); var context = new MyDbContext { Users = userSet }; var userService = new UserService(); userService.AddUser();
source share