在 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);
}
}
美洲开发银行:
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);
}
但是这个测试是错误的,我不知道如何实例化这个控制器。请帮助我!有任何问题请留言。