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

美洲开发银行:

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

但是这个测试是错误的,我不知道如何实例化这个控制器。请帮助我!有任何问题请留言。

4

1 回答 1

1

您的 Home 的构造函数包含 IDB 接口,因此您需要将它传递到那里。

由于您有接口,您可以使用模拟对象(https://stackoverflow.com/questions/37359/what-c ​​-sharp-mocking-framework-to-use )来模仿您的 IDB。

于 2013-03-15T09:09:20.913 回答