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、玩家可以在新九天作必弊...
截至目前!金虎爷辅助器,新51... 截至目前!金虎爷辅助器,新518互游插件下载-真是是真的有辅助神器(哔哩哔哩)1、下载好新518互游...
截至发稿!蜀山四川辅助脚本,福... 截至发稿!蜀山四川辅助脚本,福建天天开心辅助工具下载-真是真的是有辅助app(哔哩哔哩)1、上手简单...
随着!杭州都莱大菠萝买了挂有用... 随着!杭州都莱大菠萝买了挂有用吗,小唐家乐园辅助-真是是有辅助软件(哔哩哔哩)1、游戏颠覆性的策略玩...
2026版教学!欢乐掌心英山修... 2026版教学!欢乐掌心英山修改器,越乡游义乌辅助器免费试用-一直是真的有辅助挂(哔哩哔哩)1、上手...
教学辅助挂!微信呢小程序游戏辅... 教学辅助挂!微信呢小程序游戏辅助器,闲来山水广西辅助-好像确实有辅助技巧(哔哩哔哩)1.微信呢小程序...
为切实保障!衢州都莱辅助器免费... 为切实保障!衢州都莱辅助器免费,四川途游小程序辅助-总是存在有辅助工具(哔哩哔哩)1、很好的工具软件...
不少玩家反映!丰城双剑新版最强... 不少玩家反映!丰城双剑新版最强高分攻略,边锋老友填大坑辅助-原来真的有辅助攻略(哔哩哔哩)1、丰城双...
据悉!杭州都莱大菠萝有挂吗,创... 据悉!杭州都莱大菠萝有挂吗,创思维激k看底牌辅助-一直是真的有辅助器(哔哩哔哩);杭州都莱大菠萝有挂...
透视脚本!玉海楼茶苑游戏攻略,... 透视脚本!玉海楼茶苑游戏攻略,开心泉州免费辅助器-其实真的是有辅助软件(哔哩哔哩)1、打开软件启动之...