一个易用的.Net测试模拟库

我们在日常项目开发中,为了解耦都会采用面向接口编程,在开发过程中,可能接口具体实现还未准备好,为了尽早完成自测,这时候就需要来模拟对象来完成测试。

01 项目简介

FakeItEasy是一个.NET平台的简单mocking开源库,它提供了一个简单的方式来模拟对象和创建伪造对象,方便我们在单元测试中更容易地创建模拟对象。

该库使用非常简单,方便开发者模拟各种情况,来检查被测试的代码是否能够正确。

02 使用方法

**示例:**比如一个商城,我们需要获取商品的价格。

在三层架构里,我们就会定义仓储接口:IProductRepository,供业务服务层调用。

1、仓储接口

复制代码
/// <summary>
/// 商品仓储接口
/// </summary>
public interface IProductRepository
{
    /// <summary>
    /// 获取商品价格
    /// </summary>
    /// <param name="productId"></param>
    /// <returns></returns>
    decimal GetProductPrice(int productId);
}

2、商品服务

复制代码
/// <summary>
/// 商品服务
/// </summary>
public class ProductService
{
    private readonly IProductRepository _productRepository;
    public ProductService(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    /// <summary>
    /// 获取商品价格
    /// </summary>
    /// <param name="productId"></param>
    /// <returns></returns>
    public decimal GetPriceForProduct(int productId)
    {
        return _productRepository.GetProductPrice(productId);
    }
}

3、模拟单元测试

复制代码
using FakeItEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestMethod]
void TestMethod()
{
    //模拟创建商品仓储对象
    var productRepository = A.Fake<IProductRepository>();

    //模拟仓储获取商品价格
    A.CallTo(() => productRepository.GetProductPrice(1)).Returns(19);
    A.CallTo(() => productRepository.GetProductPrice(2)).Returns(20);

    var productService = new ProductService(productRepository);

    //验证是否正确
    var result1 = productService.GetPriceForProduct(1);
    Assert.AreEqual(result1, 19);

    //验证是否正确
    var result2 = productService.GetPriceForProduct(2);
    Assert.AreEqual(result2, 20);
}

03 项目地址

https://github.com/FakeItEasy/FakeItEasy

更多开源项目: https://github.com/bianchenglequ/NetCodeTop

我是编程乐趣,一个.Net开发经验老程序员,欢迎"关注"我,每天为你分享开源项目和编程知识。

也欢迎加入【.Net技术编程交流社区】,和大家共同学习交流!,
点击加入https://bbs.csdn.net/topics/613465368

  • End -

推荐阅读

推荐一个.Ner Core开发的配置中心开源项目

一个跨平台执行外部命令的C#开源库

一个基于.Net高性能跨平台内网穿透工具

一个C#开发的Windows远程桌面工具

一个基于.Net Core开发的适合外贸商城系统

相关推荐
码观天工1 天前
C#高性能开发之类型系统:从C# 7.0 到C# 14的类型系统演进全景
性能优化·c#·.net·memory·高性能·record·c#14·类型系统
程序员秘密基地1 天前
基于c#,wpf,ef框架,sql server数据库,音乐播放器
sql·sqlserver·c#·.net·wpf
Zhen (Evan) Wang1 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
我是唐青枫2 天前
C# 如何比较两个List是否相等?
c#·.net
时光追逐者2 天前
C#/.NET/.NET Core拾遗补漏合集(25年4月更新)
c#·.net·.netcore
Hellc0072 天前
完整的 .NET 6 分布式定时任务实现(Hangfire + Redis 分布式锁)
redis·分布式·.net
CF14年老兵2 天前
MVC 应用程序中使用 FluentValidation 进行验证的重要性
性能优化·mvc·.net
搬砖工程师Cola3 天前
<C#>.NET WebAPI 的 FromBody ,FromForm ,FromServices等详细解释
开发语言·c#·.net
时光追逐者3 天前
C#/.NET/.NET Core技术前沿周刊 | 第 35 期(2025年4.14-4.20)
c#·.net·.netcore
码观天工3 天前
.NET 原生驾驭 AI 新基建实战系列(四):Qdrant ── 实时高效的向量搜索利器
c#·.net·向量数据库·qdrant