1
在MVC4中,我使用Ninject注入控制器,我想測試「索引」。 注射的寫入(用於注射的控制器)的:如何測試索引?
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver()
{
kernel = new StandardKernel();
AddBindings();
}
private void AddBindings()
{
kernel.Bind<IDB>().To<DB>();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
}
的IDB:
public interface IDB
{
IBugTrackRepository iBugTrackRepository { get; }
ICategoryRepository iCategoryRepository { get; }
...
...
IUserRepository iUserRepository { get; }
}
爲了實現:
public class DB : IDB
{
public IBugTrackRepository iBugTrackRepository
{
get { return new BugTrackRepository(); }
}
public ICategoryRepository iCategoryRepository
{
get { return new CategoryRepository(); }
}
...
...
public IUserRepository iUserRepository
{
get { return new UserRepository(); }
}
}
爲了實現:
public class BugTrackRepository : IBugTrackRepository
{
private DBEntities context = new DBEntities();
public IQueryable<BugTrack> bugtrack
{
get { return context.BugTrack; }
}
...
//Other database operations...
}
的控制器:
public class HomeController : Controller
{
private IDB repository;
public HomeController(IDB repo)
{
repository = repo;
}
public ActionResult Index()
{
ViewBag.mytitle = "Home Page";
return View();
}
}
測試代碼:
[TestMethod]
public void TestIndex()
{
HomeController controller = new HomeController(??);
ViewResult result = controller.Index() as ViewResult;
Assert.AreEqual("Home Page", result.ViewBag.mytitle);
}
,但這個測試是錯誤的,我卻不知道如何實例化這個Controller.Please幫助我有任何問題請留言!
使用Ninject.MVC3,不要搞砸你自己的Dependency Resolver實現,生活太短。不要在變量名稱上使用'i'前綴,它們會使眼睛流血! – 2013-03-18 07:31:37