Specification Testing with EF - The ObjectContext instance has been disposed

让人想犯罪 __ 提交于 2019-12-13 05:19:27

问题


I have the following SpecFlow scenario:

[When(@"the registration is submitted")]
public void WhenTheRegistrationIsSubmitted()
{
    //var controller = _kernel.Get<AccountController>();

    var factory = new HockeyDbContextFactory();

    var userRepository = new Repository<User>(factory);
    var cryptoService = new CryptoService();
    var roleRepository = new Repository<Role>(factory);
    var playerService = new Mock<IPlayerService>();
    var leagueService = new Mock<ILeagueService>();
    var userService = new UserService(userRepository, cryptoService, roleRepository);
    var controller = new AccountController(userService, playerService.Object, leagueService.Object);

    controller.Register(_registerModel);
}

Which eventually calls the following method through my controller:

public void RegisterUser(User user)
{
    var salt = _cryptoService.GenerateSalt();
    var hasedPassword = _cryptoService.HashPassword(user.Password, salt);

    user.PasswordSalt = salt;
    user.Password = hasedPassword;

    var defaultRole = _roleRepository.GetAll().Single(x => x.RoleName == "User");
    user.Roles.Add(defaultRole);

    Insert(user);
}

All of my database calls are fine until I get to this line:

var defaultRole = _roleRepository.GetAll().Single(x => x.RoleName == "User");

When I breakpoint on that line and inspect the call to GetAll(), I have context and I can view the query. The exception occurs on the call to Single(). Now, if I stick a .Include(x => x.Users) on the call to GetAll(), I'm fine. This tells me it has something to do with lazy-loading.

The error i get is: error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

When RegisterUser is called from my web application, I'm fine. When RegisterUser is called from my specification test, it fails. Does anyone have some incite?

UPDATE:

To add a little more information, here is the controller action being called:

[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegisterModel model)
{
    if (!_userService.EmailIsUnique(model.EmailAddress))
        ModelState.AddModelError("EmailAddress", "Email Address is already in use.");

    if (!_userService.UserNameIsUnique(model.UserName))
        ModelState.AddModelError("UserName", "User Name is already in use");

    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {

            var user = Mapper.Map<User>(model);
            _userService.RegisterUser(user);
            FormsAuthentication.SetAuthCookie(model.UserName, false);

            return View("RegisterSuccess");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

stepping through the code, I never make it to FormsAuthentication.SetAuthCookie(model.UserName, false);


回答1:


I figured out what the issue was. I was seeding my test database with this step:

[BeforeFeature]
public static void BeforeFeature()
{
    MappingConfig.RegisterMappings();
    Database.SetInitializer(new TestDatabaseInitializer());
}

The context in my TestDatabaseInitializer must have been conflicting with the context I created in my scenario. Thanks for the comment Gert, it gave me the idea to take a closer look at what was going on in the rest of my scenario.



来源:https://stackoverflow.com/questions/18033303/specification-testing-with-ef-the-objectcontext-instance-has-been-disposed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!