我按照this SO answer创建了一个按顺序调用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之前这不会验证,但它只会执行边缘情况....除非我在回调中没有断言,而只是追踪和断言最后???????那可能有用,想法????
答案 0 :(得分:1)
在与一些同事交谈后,我们提出了一种双重方法,将其交给实施者。
选项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);
}
}