使用EF进行规范测试-ObjectContext实例已处置 [英] Specification Testing with EF - The ObjectContext instance has been disposed

查看:253
本文介绍了使用EF进行规范测试-ObjectContext实例已处置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下SpecFlow方案:

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

当我在该行上断点并检查对GetAll()的调用时,我具有上下文,可以查看查询。调用Single()时发生异常。现在,如果我在调用GetAll()时坚持使用 .Include(x => x.Users),那很好。这告诉我它与延迟加载有关。

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.

我得到的错误是:错误:ObjectContext实例已被处理,不能再被处理。

当从我的Web应用程序中调用RegisterUser时,我很好。从我的规范测试中调用RegisterUser时,它失败。有人有煽动性吗?

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?

更新:

要添加更多内容信息,这里是被调用的控制器操作:

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

单步执行代码,但我从未做到过 FormsAuthentication.SetAuthCookie(model.UserName,false);

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

推荐答案

我弄清楚了问题所在。我正在通过以下步骤播种测试数据库:

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

TestDatabaseInitializer中的上下文必须与我创建的上下文冲突场景。感谢Gert的评论,它给了我一个想法,让我仔细研究一下其余场景中发生的事情。

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.

这篇关于使用EF进行规范测试-ObjectContext实例已处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆