Home » excel » VBA Unit Testing

VBA Unit Testing

Posted by: admin April 23, 2020 Leave a comment


I have been writing so OO VBA code, it really helps me to write frequent unit test.
My approach to writing these tests would involve writing a Sub names ‘test_CLASSNAME’ in there I woudl instantiate my object, set parameters, and concludee with Debug.Assert.

Problem is my classes are getting bit more complicated now and I would like to run unit tests that involve Private methods & properties of the class. Using my apprach that is ofcourse not possible because I am using an external Sub to call relevant methods.

So my question is what other approaches exist to Unit testing in VBA, preferablyu ones that manage to access private methods of a class?

I came across follwing post but solutions involved installing add-ons my work policy forbids from doing that. So I was specualting that if I could create a test subclass of the class I want to be tested I could access all internal stuff( This is for example how Ruby solves this using Module Test::Unit).

For Argument Sake here is a dummy Class that I want to test

Class Dummy
  Private Priv1 as Integer
  Private Class_Init()
     Priv1 = 1
  End Sub
  Private Sub sub1()
     Priv1 = 2
  End Sub

And Here is How I would normally test this(Provided my method, and property was not private,thus in this case this is invalid):

Sub test_Dummy()
  Dim tested as New Dummy

  Debug.Assert tested.Priv1 = 1
  Debug.Assert tested.Priv1 = 2

  Debug.Print "Dummy passed all tests"
How to&Answers:

The Rubberduck project started with the porting to C# of some VBA unit-testing code which you can find right here on Code Review Stack Exchange – it won’t let you call Private methods, but if you can’t install any IDE add-ins your best bet is probably to write your own.

I’m not going to detail everything here, but I encourage you to take a look at the Code Review post I just linked to (and the other related CR posts, too) and to implement your own version of it.

As for testing Private methods… don’t do that. They’re implementation details, at a lower abstraction level than what you’re really testing. Test the Public methods that call them – if these methods work as they should, then the private methods are doing their job.