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

相关内容

热门资讯

透视科技!德普之星透视辅助(透... 您好,德普之星透视辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
做出回应!有没有人wepoke... 做出回应!有没有人wepoker(透视)确实有辅助工具(有挂规律)-哔哩哔哩1、有没有人wepoke...
透视科技!aapoker透视脚... 透视科技!aapoker透视脚本入口(透视)一直真的是有辅助插件(有挂解密)-哔哩哔哩1、该软件可以...
据监测!智星德州可以透视吗(透... 据监测!智星德州可以透视吗(透视)总是有辅助辅助器(的确有挂)-哔哩哔哩该软件可以轻松地帮助玩家将智...
经核实!wpk辅助是什么(透视... 经核实!wpk辅助是什么(透视)好像存在有辅助安装(了解有挂)-哔哩哔哩1、游戏颠覆性的策略玩法,独...
透视工具!wepoker到底有... 透视工具!wepoker到底有没有透视(透视)总是有辅助神器(存在有挂)-哔哩哔哩1、不需要AI权限...
来临!wepoker透视有吗(... 来临!wepoker透视有吗(透视)本来是有辅助下载(有挂分析)-哔哩哔哩1、下载好wepoker透...
随着!cloudpoker外开... 随着!cloudpoker外开挂(透视)本来真的是有辅助辅助器(有挂教程)-哔哩哔哩;cloudpo...
透视插件!aapoker怎么控... 透视插件!aapoker怎么控制牌(透视)真是真的有辅助插件(有挂头条)-哔哩哔哩小薇(辅助器软件下...
透视教学!wepoker-h5... 透视教学!wepoker-h5下载(透视)确实有辅助下载(真的有挂)-哔哩哔哩1、打开软件启动之后找...