我们在日常项目开发中,为了解耦都会采用面向接口编程,在开发过程中,可能接口具体实现还未准备好,为了尽早完成自测,这时候就需要来模拟对象来完成测试。
01
项目简介
FakeItEasy是一个.NET平台的简单mocking开源库,它提供了一个简单的方式来模拟对象和创建伪造对象,方便我们在单元测试中更容易地创建模拟对象。
该库使用非常简单,方便开发者模拟各种情况,来检查被测试的代码是否能够正确。
02
使用方法
示例:比如一个商城,我们需要获取商品的价格。
在三层架构里,我们就会定义仓储接口:IProductRepository,供业务服务层调用。
1、仓储接口
/// /// 商品仓储接口/// public interface IProductRepository{ /// /// 获取商品价格 /// /// /// decimal GetProductPrice(int productId);}
2、商品服务
/// /// 商品服务/// public class ProductService{ private readonly IProductRepository _productRepository; public ProductService(IProductRepository productRepository) { _productRepository = productRepository; }
/// /// 获取商品价格 /// /// /// public decimal GetPriceForProduct(int productId) { return _productRepository.GetProductPrice(productId); }}
3、模拟单元测试
using FakeItEasy;using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestMethod]void TestMethod(){ //模拟创建商品仓储对象 var productRepository = A.Fake();
//模拟仓储获取商品价格 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
领取专属 10元无门槛券
私享最新 技术干货