我是测试新手,从未使用过MSpec。我看了教程,唯一的例子是"lite",比如1 + 1 should be 2
。我需要测试这个真正的方法,我不知道从哪里开始。
public ILineItem CreateLineItem(BaseVariationContent sku, int quantityToAdd)
{
var price = sku.GetDefaultPrice();
var parent = sku.GetParentProducts().FirstOrDefault() != null ? _contentLoader.Get<ProductContent>(sku.GetParentProducts().FirstOrDefault()).Code : string.Empty;
return new LineItem
{
Code = sku.Code,
DisplayName = sku.DisplayName,
Description = sku.Description,
Quantity = quantityToAdd,
PlacedPrice = price.UnitPrice.Amount,
ListPrice = price.UnitPrice.Amount,
Created = DateAndTime.Now,
MaxQuantity = sku.MaxQuantity ?? 100,
MinQuantity = sku.MinQuantity ?? 1,
InventoryStatus = sku.TrackInventory ? (int)InventoryStatus.Enabled : (int)InventoryStatus.Disabled,
WarehouseCode = string.Empty, // TODO: Add warehouse id
ParentCatalogEntryId = parent,
};
}
BaseVariationContent
只是一个有很多属性的类,它有一个扩展。
MSpec github repo有一个非常好的README,它解释了MSpec测试类和测试用例的基本语法组件。
https://github.com/machine/machine.specifications#machinespecifications
我不会填写你的测试细节,但我会向你展示设置mspec测试的重要部分。
[Subject("Line Item")]
public class When_creating_a_basic_line_item_from_generic_sku()
{
Establish context = () =>
{
// you would use this if the Subject's constructor
// required more complicated setup, mocks, etc.
}
Because of = () => Subject.CreateLineItem(Sku, Quantity);
It should_be_in_some_state = () => Item.InventoryStatus.ShouldEqual(InventoryStatus.Enabled);
private static Whatever Subject = new Whatever();
private static BaseVariationContent Sku = new GenericSku();
private static int Quantity = 1;
private static ILineItem Item;
}
您将想要运行这些测试,所以使用命令行工具
https://github.com/machine/machine.specifications#command-线路参考
或集成之一
https://github.com/machine/machine.specifications#resharper-集成
让我带您了解一个真实的实现。假设您有一个名为SiteService的服务,它返回当前的siteId(您的应用程序有多个siteId)。
如果您想编写一个测试用例,在请求当前站点时,它应该在配置中返回站点id定义。
您将需要创建一个测试类(标准类文件),让我们给出一个有意义的名称,如"SiteServiceSpec.cs";接下来,您需要模拟ISiteConfiguration,以便它可以从SiteConfiguration 中获取站点id
public abstract class SiteServiceContext : WithFakes
{
Establish context = () =>
{
var siteConfiguration = An<ISiteConfiguration>();
siteConfiguration.WhenToldTo(x => x.Id)
.Return(CurrentSiteId);
Repository = An<IRepository<WebSite.Domain.Site.Site>>();
SUT = new SiteService(siteConfiguration, Repository);
};
protected const short CurrentSiteId = 1;
protected static SiteService SUT;
protected static IRepository<WebSite.Domain.Site.Site> Repository;
}
现在,这里是测试类的例子。
[Subject(typeof(SiteService))]
public class When_requesting_current_site : SiteServiceContext
{
It should_return_site_with_id_defined_in_configuration = () =>
Result.Id.ShouldEqual(CurrentSiteId);
Establish context = () =>
{
var site = An<WebSite.Domain.Site.Site>();
site.WhenToldTo(x => x.Id)
.Return(CurrentSiteId);
Repository.WhenToldTo(x => x.GetById(CurrentSiteId))
.Return(site);
};
Because of = () =>
Result = SUT.GetCurrentSite();
static WebSite.Domain.Site.Site Result;
}
我希望它能帮助你了解它是如何工作的。此外,遵循@anthony mastrean 提供的结构