使用EF进行规范测试 - 已经处理了ObjectContext实例

时间:2013-08-03 13:20:48

标签: c# entity-framework-5 specflow xunit

我有以下SpecFlow场景:

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

最终通过我的控制器调用以下方法:

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

我的所有数据库调用都没问题,直到我到达这一行:

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

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

我得到的错误是:错误:ObjectContext实例已被处理,不能再用于需要连接的操作。

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

更新

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

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

1 个答案:

答案 0 :(得分:0)

我弄清楚问题是什么。我正在通过这一步播种我的测试数据库:

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

我的TestDatabaseInitializer中的上下文必须与我在场景中创建的上下文冲突。感谢Gert的评论,它给了我一个想法,让我仔细看看我的其他方案中发生了什么。