模拟回调顺序边缘情况错误

本文关键字:情况 错误 边缘 顺序 回调 模拟 | 更新日期: 2023-09-27 18:19:12

我创建了一个扩展方法,根据这个SO答案按顺序调用moq(见下文)。

一个用例是:

mock.setup.CallbackSequence(new List{h,e,l,l,o})

,其中我将hello传递到SUT,并期望字符按顺序排列。

问题是:

mock.setup.CallbackSequence(new List{h,e,l,l,o,X})

,我通过hello。这将通过,即使它应该失败,因为动态断言的性质(X从未发送,但我们永远不知道)。我能想到的解决这个问题的唯一方法就是添加一个

mock.Verify(setupmethod, Times.Exactly(list.Count))

然而,回调设置和验证是在两个不同的地方完成的,因此发现这个缺陷的责任将落在扩展方法的使用者身上。我想避免把它放在他们身上,因为它注定会失败.....建议?

public static ICallbackResult CallbackSequence<TMockType, T1, T2>(this ISetup<TMockType> mockSetup, IList<T1> sequencedList) where TMockType : class
{
  //Refactor: Does not fail if it does not reach the end, only if out of order and/or too long
  var index = 0;
  return mockSetup.Callback((T1 t1, T2 t2) =>
  {
    if(index >= sequencedList.Count)
      Assert.That(false, "Sequenced list attempted to access index out of bounds. Count is " + sequencedList.Count + "; index is " + index + "; value being checked is " + t1);
    var currentItemInSequence = sequencedList[index];
    Assert.That(t1, Is.EqualTo(currentItemInSequence), String.Format("Failed sequence at position{0}", index));
    index++;
  });
}

编辑

我能想到的唯一可行的方法是返回一个消费者应该在最后调用的自定义对象:

var sequenceVerifier = ...CallbackSequence();
//Do Stuff
sequenceVerifier.VerifySequence();

这对我来说仍然不是最优的,因为这给人的印象是,这将不会验证,直到调用VerifySequence,但它只会执行边缘情况....除非我不在回调中断言,而只是在最后跟踪和断言???????这可能行得通,????

模拟回调顺序边缘情况错误

在与一些同事讨论后,我们提出了一种双重方法,将其留给实施者。

选项1

返回必须调用VerifySequenceCalls方法的SequenceVerifier

选项2

将我的操作传递给一个助手方法,以便它可以设置、操作,然后验证边缘情况

我可以在我的第二个选项中使用SequenceVerifier。然后,由消费者决定他们希望自己的代码看起来是什么样子。

public static MockSequenceVerifier<T1> CallbackInOrderOfSequence<TMockType, T1, T2>(this ISetup<TMockType> mockSetup, IList<T1> sequencedList) where TMockType : class
{
  var mockSequenceVerifier = new MockSequenceVerifier<T1>(sequencedList);
  mockSetup.Callback((T1 t1, T2 t2) => mockSequenceVerifier.UpdateSequence(t1));
  return mockSequenceVerifier;
}
public static void VerifySequenceAfterActionPerformed<TMockType, T1, T2>(this ISetup<TMockType> mockSetup, IList<T1> sequencedList, Action actionToPerform) where TMockType : class
{
  var verifier = CallbackInOrderOfSequence<TMockType, T1, T2>(mockSetup, sequencedList);
  actionToPerform();
  verifier.VerifySequence();
}
public class MockSequenceVerifier<T>
{
  private IList<T> SequenceToVerifyAgainst { get; set; } 
  private IList<T> ActualSequence { get; set; } 
  public MockSequenceVerifier(IList<T> sequenceToVerifyAgainst)
  {
    SequenceToVerifyAgainst = sequenceToVerifyAgainst;
    ActualSequence = new List<T>();
  } 
  public void VerifySequence()
  {
    ActualSequence.IsEqualTo(SequenceToVerifyAgainst);
  }
  public void UpdateSequence(T item)
  {
    ActualSequence.Add(item);
  }
}