mercredi 22 juin 2016

Testing property used on mvc controller after injection

public class MyUser: IIdentity, IMyUser{
   // ommited for abbrev.       
}

public interface IMyUser
{
    int Id { get; set; }
    int? CompanyId { get; set; }        
}

inside MyController I'm using MyUser besides others to populate comboboxes

public ActionResult Details(int? subsidId = null, int? req = null)
 {
    ...
    MyUser user = ....;
    var obj1 = ... // ommited on purpose for abbrev.    
    populateCombos(subsidId, user.CompanyId, req); 
 }

I'm getting exception on this line populateCombos cause user object is always null. Inside same controller I'm injecting interface which IMyUser implements

[Inject]
public IMyUser MyUser { get; set; }

this property is correctly binded using ninject (like others in my app)

kernel.Bind<IMyUser>().To<MyUser>().InRequestScope();

now on testing project I'm initializing controller with mocking requested dependencies

[SetUp]
public void Setup()
{
   _controller = new MyController(){
       ... repositories....
       MyUser = MockMyUser()
   }
}

private IMyUser MockMyUser()
{
    var u = new Mock<IMyUser>();
    u.SetupGet(x => x.Id).Returns(1);      
    u.SetupGet(x => x.CompanyId).Returns(99);    

    return u.Object;
}

and inside test method I wrote simple test

[Test]
public void CanDoDetails()
{
   ViewResult res = this.controller.Details(1, 2) as ViewResult;  

   var model = result.Model as MyModel;            

   Assert.IsNotNull(model);
}

Question is:

why I'm getting this dependency (MyUser inside MyController as null) cause it's injected properly? What I'm doing wrong?

Aucun commentaire:

Enregistrer un commentaire