Ok, so now we have just created a test for creating an instance of a FormListener class, but there’s nothing in the class yet.
What do we want to test next? I need to think about the next bit of functionality I will want in this class in a way that I can test it. So I need to set it up to listen to form events of any form. In particular, I think I want to be able to do something in the BeforeUpdate event to check the bound fields before they are updated but after the user has entered or selected or put a new value of some sort into the field.
Well, the first thing I see when looking at my new class is that it doesn’t have an “Option Explicit” instruction at the top, so, I’m adding that. This will cause the compiler to fail if I don’t explicitly define my variables before using them This helps in preventing weird bugs like mistyping a variable name and having VBA interpret it as a brand new variable. Good.
Next, I guess we will want to initialize the class by passing it a Form to listen to. So my next test will be to try to run the “Setup” Method of the new class. VBA doesn’t have ways to initialize classes with parameters when you call them, however, it does have a Class Initialize event which occurs when you first create a new instance of the class. In our case though, this is not helpful as we want to initialize it with a Form to listen to. So here’s the next test:
'@TestMethod("FormListener") Private Sub SetupFormListener() On Error GoTo TestFail 'Arrange: Dim FormListenerTest As New FormListener Dim NewForm As New Access.Form 'Act: FormListenerTest.Setup NewForm 'Assert: Assert.Succeed TestExit: '@Ignore UnhandledOnErrorResumeNext On Error Resume Next Exit Sub TestFail: Assert.Fail "Test raised an error: #" & Err.Number & " - " & Err.Description Resume TestExit End Sub
In this case, I simply updated the TestMethod line at the top in my prior Test, then copied and pasted the whole test and modified the name to SetupFormListener and changed the Arrange and Act sessions to tell the object what it needs to do. Setup with the new form.
I tell RubberDuck to Run All Tests and it comes back with a compiler error telling me .Setup isn’t a method of FormListener. So I’ll add it. Of course it doesn’t compile either because I have to provide a parameter in the Setup method to take an Access Form. So once I provide my parameter my class code looks like this:
Option Compare Database Option Explicit Public Sub Setup(theForm As Access.Form) End Sub
And my test still doesn’t pass!