ASP.NETMVC:如何在数据驱动环境中模拟数据库?
创始人
2024-11-12 05:30:19
0

在ASP.NET MVC中,可以使用Moq库来模拟数据库以进行单元测试。以下是一些示例代码:

首先,创建一个存储库接口,该接口将定义所有您需要模拟的数据库操作:

public interface IProductRepository { IEnumerable GetAllProducts(); Product GetProductById(int productId); void AddProduct(Product product); void UpdateProduct(Product product); void DeleteProduct(int productId); }

然后实现该接口的类:

public class ProductRepository : IProductRepository { private List products = new List() { new Product() {ProductId = 1, ProductName = "iPhone X"}, new Product() {ProductId = 2, ProductName = "Samsung Galaxy S9"}, new Product() {ProductId = 3, ProductName = "Google Pixel 2"} };

public void AddProduct(Product product)
{
    products.Add(product);
}

public void DeleteProduct(int productId)
{
    var product = products.FirstOrDefault(x => x.ProductId == productId);
    if (product != null)
        products.Remove(product);
}

public IEnumerable GetAllProducts()
{
    return products;
}

public Product GetProductById(int productId)
{
    return products.FirstOrDefault(x => x.ProductId == productId);
}

public void UpdateProduct(Product product)
{
    var old_product = products.FirstOrDefault(x => x.ProductId == product.ProductId);
    if (old_product != null)
    {
        products.Remove(old_product);
        products.Add(product);
    }
}

}

这是一个简单的Product模型:

public class Product { public int ProductId { get; set; } public string ProductName { get; set; } }

现在,我们可以使用Moq来模拟这个存储库以进行单元测试:

[TestClass] public class ProductControllerTests { [TestMethod] public void Index_ReturnsAViewResult_WithAListOfProducts() { // Arrange var mockRepo = new Mock(); mockRepo.Setup(repo => repo.GetAllProducts()) .Returns(GetTestProducts()); var controller = new

相关内容

热门资讯

微信小程序黑科技免费!微乐小程... 微信小程序黑科技免费!微乐小程序晃晃脚本(开挂)技巧-果然揭幕真的是有挂1、进入到是否有挂之后,能看...
微信小程序微乐破解器!微乐自建... 微信小程序微乐破解器!微乐自建房辅助工具(开挂)app-果然专业真的有挂透视方法中分为三种模型:靠谱...
微乐小程序存在有挂!微乐家乡小... 微乐小程序存在有挂!微乐家乡小程序辅助(开挂)方法-果然科普是真的挂1、免费辅助多个强度级别选择2、...
微信小程序微乐破解器!微乐春天... 微信小程序微乐破解器!微乐春天小程序辅助(开挂)神器-果然透视真的有挂1、游戏颠覆性的策略玩法,独创...
微信小程序黑科技免费!微乐斗地... 微信小程序黑科技免费!微乐斗地主有挂吗(开挂)神器-切实透视是有挂1、公共底牌简单,透视插件操作,插...
微乐小程序真的有挂!微乐自建房... 微乐小程序真的有挂!微乐自建房安装挂(开挂)插件-一直科普存在有挂1、许多玩家不知道辅助怎么退出观战...
微乐小程序透视辅助!微乐自建房... 微乐小程序透视辅助!微乐自建房免费黑科技推荐(开挂)插件-好像曝光真的有挂1、辅助软件下载优化,底牌...
微信小程序黑科技免费!微乐小程... 微信小程序黑科技免费!微乐小程序黑科技(开挂)app-真是有挂真的是有挂1、进入游戏-大厅左侧-新手...
微乐小程序透视挂!微乐自建房辅... 微乐小程序透视挂!微乐自建房辅助工具别人怎么看(开挂)方法-本来科普是有挂1、金币登录送、破产送、升...
微乐小程序透视辅助!微乐小程序... 微乐小程序透视辅助!微乐小程序外辅助工具(开挂)攻略-其实揭露真的有挂1、打开软件启动之后找到中间准...