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

相关内容

热门资讯

一分钟揭秘!天天互娱网络科技,... 一分钟揭秘!天天互娱网络科技,wepoker代打辅助机器人,详细教程(有挂秘诀);一分钟揭秘!天天互...
一分钟了解!乐酷副厅辅助,闲逸... 一分钟了解!乐酷副厅辅助,闲逸亲友圈辅助下载(果然是真的有挂)1、在闲逸亲友圈辅助下载插件功能辅助器...
今日焦点!方片十三张外挂,聚星... 【福星临门,好运相随】;今日焦点!方片十三张外挂,聚星ai辅助工具激活码,新2025版(有挂秘笈);...
分享开挂内幕!闲逸辅助软件下载... 分享开挂内幕!闲逸辅助软件下载苹果,天天爱柳州麻将辅助器(竟然有挂)1、闲逸辅助软件下载苹果免费脚本...
终于知道!九酷众游辅助,hhp... 您好,九酷众游辅助这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款...
玩家必备攻略!微乐小程序微乐房... 玩家必备攻略!微乐小程序微乐房间怎么开挂,波特互娱辅助(本来是有挂)1、微乐小程序微乐房间怎么开挂辅...
科技通报!哈狗智能辅助,hhp... 科技通报!哈狗智能辅助,hhpoker真的有透视吗,解密教程(有挂分享);1、这是跨平台的哈狗智能辅...
玩家必看科普!闲逸碰胡辅助器,... 玩家必看科普!闲逸碰胡辅助器,边锋透视器(总是真的是有挂)1、超多福利:超高返利,海量正版游戏,闲逸...
重磅来袭!开心赢三张自建房有挂... 您好:开心赢三张自建房有挂吗这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
每日必看!道游互娱透视辅助截图... 每日必看!道游互娱透视辅助截图,老友广东辅助工具(竟然是有挂)所有人都在同一条线上,像星星一样排成一...