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

相关内容

热门资讯

透视解谜"xpoke... 透视解谜"xpoker辅助怎么用"总是是真的辅助教程(哔哩哔哩)1、下载好xpoker辅助怎么用正确...
事发当天"wpk模拟... 事发当天"wpk模拟器是什么"wepoker辅助器怎么弄(真是是真的辅助下载)-哔哩哔哩所有人都在同...
透视解谜"wepok... 透视解谜"wepoker好友房开挂"其实真的有辅助挂(哔哩哔哩)1、wepoker好友房开挂免费脚本...
今日"悦扑克脚本&q... 今日"悦扑克脚本"wepokerplus开挂(本来是真的辅助插件)-哔哩哔哩1、任何wepokerp...
透视了解"we-po... 透视了解"we-poker是什么软件"确实是真的辅助软件(哔哩哔哩)1、we-poker是什么软件破...
辅助透视"wepok... 辅助透视"wepoker买钻石有用吗"wepoker能不能透视(都是存在有辅助软件)-哔哩哔哩进入游...
透视总结"wepok... 透视总结"wepoker透视底牌脚本"本来真的是有辅助技巧(哔哩哔哩)该软件可以轻松地帮助玩家将we...
透视好牌"拱趴大菠萝... 透视好牌"拱趴大菠萝万能辅助器"购买的wpk辅助在哪里下载(一直存在有辅助下载)-哔哩哔哩1、很好的...
透视解密"德州局脚本... 透视解密"德州局脚本"切实存在有辅助教程(哔哩哔哩)1、超多福利:超高返利,海量正版游戏,德州局脚本...
透视智能ai"aap... 透视智能ai"aapoker脚本怎么用"wepoker免费辅助器(一直是真的辅助平台)-哔哩哔哩一、...