如何添加到模拟存储库

用户名

我正在使用MVC 4创建一个应用程序。

我有以下Mock存储库

Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new List<Product>
{
    new Product { Name = "FootBall", Price=25 },
    new Product { Name = "Surf board", Price=179 },
    new Product { Name = "Running shoes", Price=25 },
}.AsQueryable());

ninjectKernel.Bind<IProductRepository>().ToConstant(mock.Object);

在我的控制器中,如何向该存储库添加新产品?

公共类ProductController:控制器{私有IProductRepository存储库;

    public ProductController(IProductRepository productRepository)
    {

        repository = productRepository;

    }

    public ViewResult List()
    {
        return View(repository.Products);
    }

    public ViewResult Add()
    {
       var newProduct = new Product
        {
            Name = "Sneakers", Price = 30
        };


      //how do I add this newProduct to the repository?

    }

}

我将以下内容添加到IProductRepository

 public interface IProductRepository
    {
        IQueryable<Product> Products();

        void AddProducts(Product product);
    }

 public class ProductRepository : IProductRepository
    {

        public IQueryable<Product> Products()
        {

           //how do I access the repo?


        }

        public void AddProducts(Product product)
        {


             //how do I access the repo?

        }
    }
内迪·意大利面

在您的控制器中,您可以执行以下操作:

    public class ProductRepository : IProductRepository
    {
        List<Product> data = new List<Product>
        {
            new Product { Name = "FootBall", Price=25 },
            new Product { Name = "Surf board", Price=179 },
            new Product { Name = "Running shoes", Price=25 }
        };

        public IQueryable<Product> Products()
        {

          return this.data.AsQueryable();

        }

        public void AddProducts(Product product)
        {
            this.data.Add(product);
        }
    }

如果您要修改数据,则模拟将不起作用,除非您在某个位置保留了对列表的引用,并且已在控制器的Add方法中访问了该列表

更新

为了确保您使用相同的存储库,请将ninjectKernel始终配置为返回相同的存储库

ninjectKernel.Bind<IProductRepository>().ToConstant(new ProductRepository())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用 AddTransient 将存储库添加到服务

如何将Linuxmint存储库添加到Ubuntu?

如何确保添加到Linux Mint的存储库是安全的

记录而不添加到存储库?

将包含添加到存储库

如何将我的新存储库正确添加到 github - 未找到存储库

如何将远程存储库添加到我自己的git存储库中

如何将照片添加到iOS模拟器以测试使用巨大的照片库?

如何将本地存储库上的其他文件添加到现有远程存储库

Sublime Text如何将软件包添加到全局存储库

PHP MySql 准备语句......如何更新数据库,添加到已经存储的值

如何将版本信息添加到作为ZIP存档分发的git存储库中?

如何将身份验证证书添加到存储库

如何将内置的休眠模式添加到本地Maven存储库中?

如何将2个Java项目添加到相同的位存储库

如何将屏幕快照添加到github存储库中的自述文件中?

如何在文件首次添加到Git存储库时列出文件?

如何将Archassault存储库添加到Arch Linux

如何在Eclipse中将Redmine和Jenkins作为任务存储库添加到Mylyn?

如何将自定义Maven存储库添加到Gradle

如何使用PCF将QueueManager作为部分存储库添加到群集中?

如何将子模块添加到github存储库

如何将Java代码从Eclipse添加到git存储库

如何将软件包添加到我的Lerna存储库?

如何将克隆的 git 存储库 zip 文件添加到 Azure devops?

如何将RPM Fusion和Livna存储库添加到Fedora?

如何将我的github存储库的链接添加到npm包中?

如何将文件和文件夹添加到GitHub存储库中?

如何使用GitHub API将文件添加到Git存储库?