雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

.Net测试模拟库FakeItEasy用法示例

2024-09-13 14

FakeItEasy简介

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

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

使用 FakeItEasy,可以创建模拟对象,这些对象可以替代实际的对象,用于测试。

FakeItEasy 的主要功能包括:

创建模拟对象:FakeItEasy 提供了丰富的 API,可以用于创建各种类型的模拟对象。 配置模拟对象的行为:FakeItEasy 提供了灵活的机制,可以配置模拟对象的行为。 断言模拟对象的行为:FakeItEasy 提供了丰富的断言,可以用于断言模拟对象的行为。

FakeItEasy使用方法

​下面是一个使用FakeltEasy的示例:

比如一个商城,我们需要获取商品的价格。在三层架构里,我们就会定义​仓储接口: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);
}

FakeItEasy GitHub地址

https://github.com/FakeItEasy/FakeItEasy

更新于:5天前
赞一波!

文章评论

全部评论