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

相关内容

热门资讯

透视辅助!wpk透视辅助软件,... 透视辅助!wpk透视辅助软件,aapoker透视脚本下载,实测揭晓(有挂规律);1、玩家可以在wpk...
透视安卓版!德普之星透视辅助软... 透视安卓版!德普之星透视辅助软件,wpk透视辅助靠谱吗,一分钟了解(有挂透明)1、在wpk透视辅助a...
透视辅助!红龙poker辅助,... 透视辅助!红龙poker辅助,wpk辅助器安装,实操分享(有挂介绍)是一种具有地方特色的麻将游戏,要...
透视攻略!wepoker辅助下... 透视攻略!wepoker辅助下载,aapoker透视软件,今日百科(有挂透明)1. ai辅助创建新账...
透视了解!aapoker辅助挂... 透视了解!aapoker辅助挂,aapoker透视插件下载,记者揭秘(有挂教学);1、aapoker...
透视好牌!wepoker透视脚... 透视好牌!wepoker透视脚本网页,智星德州辅助译码插件靠谱吗,查到实测辅助(有挂黑科技)该软件可...
透视玄学!wepoker免费透... 透视玄学!wepoker免费透视脚本,wepoker辅助工具,玩家爆料(有挂黑科技)透视玄学!wep...
透视透视!hhpoker辅助下... 透视透视!hhpoker辅助下载,红龙poker有辅助吗,实测交流(有挂攻略)1、下载好辅助软件之后...
透视透视!wpk辅助工具下载,... 透视透视!wpk辅助工具下载,wepoker底牌透视脚本app,科技揭秘(有挂辅助挂);是一种具有地...
透视辅助!hhpoker透视下... 透视辅助!hhpoker透视下载链接在哪里,hhpoker透视下载链接在哪里,实操分享(有挂技巧)1...