【问题标题】:How do I write my first serious test with MSpec?如何使用 MSpec 编写我的第一个严肃测试?
【发布时间】:2015-11-13 15:13:25
【问题描述】:

我是测试新手,从未使用过 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 只是一个有很多属性并且有扩展的类。

【问题讨论】:

  • 您是否编写了 any 具有基本功能的测试来让您习惯它们的工作方式?您从哪个级别接近这个?
  • 这是我的第一次测试
  • 在这种情况下,真的听起来你需要找到一个关于编写测试的教程并从那里开始 - 在 Stack Overflow 上从头开始这样做真的太宽泛了。
  • 是的,我明白,但在任何教程中,唯一的例子是 lite 1 + 1 应该是“2”。

标签: c# unit-testing episerver mspec commerce


【解决方案1】:

MSpec github repo 有一个很好的自述文件,它解释了 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-line-reference

或其中一种集成

https://github.com/machine/machine.specifications#resharper-integration

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多