我如何使用MSpec编写我的第一个严肃测试?

时间:2015-11-13 15:13:25

标签: c# unit-testing episerver mspec commerce

我是测试的新手,从未使用过MSpec。我查看了教程,唯一的例子是&#34; lite&#34;,如<table> <tr> <?php for ($i=0; $i <= 3; $i++){ ?> <td<?php if ($i < 2) echo ' id="1"'; else echo ' id="2"'; ?>>some content to repeat</td> <?php if ($i == 1){ echo '</tr><tr>'; } ?> <?php } ?> </tr> </table> 。我需要测试这种真实的方法,但我不知道从哪里开始。

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, }; } 只是一个具有很多属性且具有扩展名的类。

1 个答案:

答案 0 :(得分:3)

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