使用 Pex 测试更改的参考参数

Testing changed reference parameters using Pex

从特性测试的角度来看,Pex 看起来很有趣,但我很难让它断言通过引用传递的对象中的更改。

鉴于我正在尝试测试以下代码:

public class ItemUpdater
{
    public void Update(Item item)
    {
        if (item.Name == "Two Times")
        {
            item.Quantity = item.Quantity*2;
        }
        if (item.Name == "Two more") {
            item.Quantity = item.Quantity + 2;
        }
    }
}

public class Item
{
    public string Name { get; set; }
    public int Quantity { get; set; }
}

我要做的是针对更新创建 运行 智能测试,这将生成 Characterisation/Locking 测试,以便我可以进行更改。

生成测试时,我得到:

 [TestClass]
    [PexClass(typeof(ItemUpdater))]
    [PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
    [PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
    public partial class ItemUpdaterTest
    {

        /// <summary>Test stub for Update(Item)</summary>
        [PexMethod]
        public void UpdateTest([PexAssumeUnderTest]ItemUpdater target, Item item) {
            PexAssume.IsNotNull(item);

            target.Update(item);

            var quality = item.Quantity;
            PexAssert.AreEqual(quality, item.Quantity);
            // TODO: add assertions to method ItemUpdaterTest.UpdateTest(ItemUpdater, Item)
        }
    }

我添加了一个假设来删除空检查测试,这里没问题。

我遇到的问题是让 intellitest 自动生成 item.Quantity 断言。我也试过将质量作为参数传递给 UpdateTest(...., int quality) 但这总是设置为零。

结果是:

[TestMethod]
[PexGeneratedBy(typeof(ItemUpdaterTest))]
public void UpdateTest515()
{
    ItemUpdater s0 = new ItemUpdater();
    Item s1 = new Item();
    s1.Name = "Two more";
    s1.Quantity = 0;
    this.UpdateTest(s0, s1);
    Assert.IsNotNull((object)s0);
}

没有断言 item.Quantity 的值。

有谁知道如何让 Pex/Intellitest 在调用 Update 方法后针对返回的 item.Quality 生成断言?

我知道怎么做了。答案是像这样添加 PexObserve.ValueAtEndOfTest:

[TestClass]
    [PexClass(typeof(ItemUpdater))]
    [PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
    [PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
    public partial class ItemUpdaterTest
    {

        /// <summary>Test stub for Update(Item)</summary>
        [PexMethod]
        public void UpdateTest([PexAssumeUnderTest]ItemUpdater target, Item item) {
            PexAssume.IsNotNull(item);

            target.Update(item);

            var testable = item;
            PexObserve.ValueAtEndOfTest("Quantity", testable.Quantity);
        }
    }

这将生成测试参数的代码。

请按照此处的说明使用 PexObserve.ValueAtEndOfTest:https://msdn.microsoft.com/en-us/library/dn885804.aspx. Please see the blogpost for reference as well: http://blogs.msdn.com/b/visualstudioalm/archive/2015/08/14/intellitest-hands-on.aspx