我目前正在使用 SpecFlow 学习/测试 BDD,效果很好!
在我选择问我的问题之前,我已经阅读了this one
,我觉得我不得不问我的问题,尽管同样的问题已经得到解决,因为Exception
没有提到的场景。
我实际上正在测试这种情况:
Scenario: I should get an error whenever I try to remove an item from an empty stack
Given I have an empty stack
When I pop from it
Then I should get an error
public class StackBehaviour {
public void GivenIHaveAnEmptyStack() { stack = new CustomStack<string>(); }
// This will throw whenever called!
// So the Then method will never be run!
// I feel like I should just put a comment which says why it's empty,
// allowing a fellow programmer to understand the exact intention.
public void WhenIPopFromIt() { stack.Pop(); }
// It is here that it verifies whether the CustomStack meets the expected behaviour.
public void ThenIShouldGetAnError() {
Assert.Throws<IndexOutOfRangeException>(delegate {
stack.Pop();
});
}
private CustomStack<string> stack;
}
public class CustomStack<T> {
public T Pop() {
if (stack.Count == 0)
throw new IndexOutOfRangeException("Cannot pop from an empty stack!");
T item = stack[stack.Count-1];
stack.RemoveAt(stack.Count-1);
return item;
}
private ArrayList stack = new ArrayList();
}
我认为在When
方法中留下注释是正确的,这样业务需求就不会缺少任何信息,并且在后面的代码上,我通过注释明确了我的意图。
你怎么看?任何其他想法为什么我不应该这样做?