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

相关内容

热门资讯

透视免费!aapoker万能辅... 透视免费!aapoker万能辅助器(透视)脚本(一贯存在有挂)一、aapoker万能辅助器AI软件牌...
透视苹果版!aa poker辅... 透视苹果版!aa poker辅助(透视)插件下载(都是真的是有挂)1、aa poker辅助ai辅助优...
透视辅助!aapoker脚本怎... 透视辅助!aapoker脚本怎么用(透视)透视方法(真是是有挂)所有人都在同一条线上,像星星一样排成...
透视线上!aa poker透视... 透视线上!aa poker透视软件(透视)插件(一贯是有挂);1、金币登录送、破产送、升级送、活动送...
透视教学!aapoker辅助器... 透视教学!aapoker辅助器怎么用(透视)插件下载(其实存在有挂)aapoker辅助器怎么用辅助器...
透视存在!aapoker脚本怎... 透视存在!aapoker脚本怎么用(透视)插件下载(切实真的有挂)1、aapoker脚本怎么用机器人...
透视挂透视!aapoker插件... 透视挂透视!aapoker插件下载(透视)透视脚本入口(切实有挂)1、aapoker插件下载ai机器...
透视有挂!aapoker脚本怎... 透视有挂!aapoker脚本怎么用(透视)透视脚本入口(都是有挂);1、游戏颠覆性的策略玩法,独创攻...
透视科技!aapoker辅助工... 透视科技!aapoker辅助工具安全吗(透视)免费透视脚本(确实真的有挂)运aapoker辅助工具安...
透视神器!aapoker辅助器... 透视神器!aapoker辅助器怎么用(透视)ai插件(竟然真的是有挂);1、这是跨平台的aapoke...