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、...
透视玄学!werplan有挂吗... 透视玄学!werplan有挂吗(透视)奇迹陕西游戏辅助器(竟然真的是有辅助神器)-哔哩哔哩1、操作简...
最终!德州私人局怎么透视(透视... 最终!德州私人局怎么透视(透视)福建天天开心辅助网(竟然有辅助神器)-哔哩哔哩1、福建天天开心辅助网...
目前!德普之星透视(透视)盛世... 目前!德普之星透视(透视)盛世2辅助工具(切实存在有辅助安装)-哔哩哔哩1、起透看视 盛世2辅助工具...
更值得关注的是!智星德州插件(... 更值得关注的是!智星德州插件(透视)顺欣茶楼智能辅助器(原来是真的辅助神器)-哔哩哔哩1、顺欣茶楼智...
据相关数据显示!德普之星透视辅... 据相关数据显示!德普之星透视辅助软件激活码(透视)新九哥脚本下载(好像真的有辅助辅助器)-哔哩哔哩1...
日前!红龙poker作必弊指令... 日前!红龙poker作必弊指令(透视)海豹大厅超级三加一辅助(其实是有辅助软件)-哔哩哔哩1、玩家可...
网友热议!约局吧德州有挂吗(透... 网友热议!约局吧德州有挂吗(透视)红人阁自动挂机脚本(确实是真的辅助软件)-哔哩哔哩1、操作简单,无...
透视辅助!破解辅助插件wepo... 透视辅助!破解辅助插件wepoker(透视)开心十三张脚本(原来有辅助app)-哔哩哔哩开心十三张脚...
于此同时!wepoker俱乐部... 于此同时!wepoker俱乐部辅助器(透视)圣盛荆州晃晃三五七辅助(总是有辅助软件)-哔哩哔哩1、下...