-
Notifications
You must be signed in to change notification settings - Fork 45
TDD Example
Testing an Add macro
-
Stub out the
Addmethod with the desired signature (input and output types), but leave the method body blank. (You want to set up the tests before writing any code)Function Add(A As Double, B As Double) As Double End Function
-
Add initial specs for the method
Sub Specs() ' Create a new collection of specs On Error Resume Next Dim Specs As New SpecSuite ' Describe the desired behavior With Specs.It("should add two numbers") ' Test the desired behavior .Expect(Add(2, 2)).ToEqual 4 .Expect(Add(3, -1)).ToEqual 2 .Expect(Add(-1, -2)).ToEqual -3 End With ' Run the specs inline (in the Immediate window) InlineRunner.RunSuite Specs End Sub
-
(Red) Open the immediate window (Ctrl+g or View > Immediate Window) and run the specs (F5) before writing the
Addmethod to verify that the tests are currently failing (running properly since no code has been written yet)= FAIL (1 of 1 failed) ========================== X should add 2 numbers Expected 0 to equal 4 Expected 0 to equal 2 Expected 0 to equal -3 === ' Failure is a good thing! It means our tests are working since we haven't written Add yet
-
(Green) Write just enough in the
Addmethod for the specs to pass and then re-run the specs (F5)Function Add(A As Double, B As Double) As Double Add = A + B End Function = PASS (1 of 1 passed) ========================== ' Success!
-
(Refactor) Let's say you wanted to expand the Add method to allow for any number of arguments. Start with a refactor of the currently tested behavior.
Function Add(ParamArray Values() As Variant) As Double Add = Values(0) + Values(1) End Function = PASS (1 of 1 passed) ========================== ' Success!
-
Then add specs for the desired new behavior that will fail initially
Sub Specs() On Error Resume Next Dim Specs As New SpecSuite With Specs.It("should add two numbers") .Expect(Add(2, 2)).ToEqual 4 .Expect(Add(3, -1)).ToEqual 2 .Expect(Add(-1, -2)).ToEqual -3 End With With Specs.It("should add any number of numbers") .Expect(Add(1, 2, 3)).ToEqual 6 .Expect(Add(1, 2, 3, 4)).ToEqual 10 End With InlineRunner.RunSuite Specs End Sub = FAIL (1 of 2 failed) ========================== X should add any number of numbers Expected 3 to equal 6 Expected 3 to equal 10 === ' Failure is ok, we haven't written this functionality yet
-
Then work on
Adduntil all of the specs passPublic Function Add(ParamArray Values() As Variant) As Double Dim i As Integer Add = 0 For i = LBound(Values) To UBound(Values) Add = Add + Values(i) Next i End Function = PASS (2 of 2 passed) ========================== ' Woohoo!