软件测试_对于堆栈的单元测试
转自 http://www.51testing.com/html/80/n-3726280.html
(1)往一个空栈中`Push`数据,该操作成功的话栈应该不空,并且栈顶元素就是刚`Push`进去的那个数据。
(2)连续地往栈中`Push`数据,每次操作后查看栈顶元素都是刚刚放进去的那个数据。
(3)往栈中`Push`特殊的数据,我们这里存放的是`string`,所以添加`string.Empty`和`null`也应该是成功的。
(4)连续地`Pop`操作,确认每次取出的都是栈顶元素。
(5)对空栈进行`Pop`或`Top`操作,会抛出异常。
类
// StackExercise Class namespace FirstUnitTest { public class StackExercise { private List<string> _stack; public StackExercise() { _stack = new List<string>(); } public void Push(string str) { _stack.Add(str); } public void Pop() { if (Empty()) { throw new InvalidOperationException("Empty stack cannot pop"); } _stack.Remove(_stack.Last()); } public string Top() { if (Empty()) { throw new InvalidOperationException("Empty stack cannot get top"); } return _stack.Last(); } public bool Empty() { return (!_stack.Any()); } }
测试类
namespace FirstUnitTest { [TestClass] public class TestStackExercise { [TestMethod] public void Test_SuccessAndNotEmpty_AfterPush() { // Arrange var stack = new StackExercise(); var testElement = "testElement"; // Action stack.Push(testElement); // Assert Assert.IsFalse(stack.Empty()); Assert.AreEqual(testElement, stack.Top()); } [TestMethod] public void Test_Success_PushMoreThanOnce() { // Arrange var stack = new StackExercise(); var testElement = "testElement_{0}"; // Action & Assert for (int i = 0; i < 10; ++i) { stack.Push(string.Format(testElement, i)); Assert.AreEqual(string.Format(testElement, i), stack.Top()); } } [TestMethod] public void Test_Success_PushEmptyString() { // Arrange var stack = new StackExercise(); string emptyString = string.Empty; string nullString = null; // Action & Assert stack.Push(emptyString); Assert.AreEqual(emptyString, stack.Top()); stack.Push(nullString); Assert.AreEqual(nullString, stack.Top()); } [TestMethod] public void Test_Success_PopLastTwoElements() { // Arrange var stack = new StackExercise(); var testElement1 = "test1"; var testElement2 = "test2"; // Action & Assert stack.Push(testElement1); stack.Push(testElement2); Assert.AreEqual(testElement2, stack.Top()); stack.Pop(); Assert.IsFalse(stack.Empty()); Assert.AreEqual(testElement1, stack.Top()); stack.Pop(); Assert.IsTrue(stack.Empty()); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Test_ThrowException_PopFromEmptyStack() { var stack = new StackExercise(); stack.Pop(); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Test_ThrowException_TopFromEmptyStack() { var stack = new StackExercise(); stack.Top(); } } }