mercredi 1 juin 2016

MOQ Testing DBContext via controller and calls , context is null?

Currently trying to write some tests using MOQ; I have an MVC application and two seperate class libraries: Business Logic Layer and Data Access Layer.

Here is my controller:

  [HttpPost]
    public ActionResult Create(UserCreateEditViewModel x)
    {

        var errors = ModelState.Values.SelectMany(v => v.Errors);
        if (ModelState.IsValid)
        {
            _businessLogicService.CreateUser(x.ObjUser.CreateDTO());
        }
        return RedirectToAction("Index", "Home");
    }

Business Layer:

 public UserDTO CreateUser(UserDTO UserObj)
    {

        var userEntity = Helpers.DTOtoEntity.User(UserObj);
        _service.AddUser(userEntity);

        return Helpers.EntitytoDTO.User(userEntity);
    }

Data Access Layer:

  public void AddUser(User userObj)
    {

        using (var db = new CoreEntities())
        {
            db.Users.Add(userObj);
            db.SaveChanges();
        }
    }

So i've wrote a basic test in MOQ (here's a snippet)

  var mockContext = new Mock<DAL.Entities.CoreEntities>();
        mockContext.Setup(c => c.Users).Returns(mockUserSet.Object);
        mockContext.Setup(c => c.Roles).Returns(mockRoleSet.Object);
        mockContext.Setup(c => c.Platforms).Returns(mockPlatformSet.Object);


        //Mock the service in DAL
        var _DALservice = new DAL.Service(mockContext.Object);


        var Controller = new UserController();
        var result = Controller.Create(new UserCreateEditViewModel { ObjUser = myUser }) as RedirectToRouteResult;

Now the trouble i've got is the controller calls another couple of methods such as getting other entities back and what not, but as i've already disposed of the context in the AddUser method an error tells me the context is null.

Do I need to recreate the fake dbContext everytime I call the service?

I've experimented passing the context through the controller but this results in the same error.

For example, when redirecting to the Index page I do a call to the service again to get a list of other objects I need to display; but the context is null.

Aucun commentaire:

Enregistrer un commentaire