2023 09 14

This post is up a little later than I wanted it to be, and it’s a short one. I expect to get in a rythm eventually, but as I’m building up momentum, some of my posts might be on the shorter and/or later side.

Last time, we took the very first steps in building up a simple unit testing framework. Get caught up here.

The first thing we want to do is update the test (the main function, in this case) to use the actual test interface run() instead of calling the method directly, like we are now. Instead of test.testMethod(), we’ll just call test.run(). Our test won’t compile until we implement the run function, which we’ll do in the simplest and quickest way that gets us to green:

func (t *test) run() {
	t.testMethod()
}

Breaking it up

Now let’s refactor this. I think this is a good place to separate out our code that defines the test type into its own file. We could have done this from the beginning, but I wanted to keep things extremely simple to start.

I moved the following code into a dedicated file called Test.go:

package main

type Test struct {
	name   string
	wasRun bool
}

func NewTest(name string) *Test {
	test := Test{name: name}
	test.wasRun = false
	return &test
}

func (t *Test) testMethod() {
	t.wasRun = true
}

func (t *Test) Run() {
	t.testMethod()
}

Note that I’ve changed some of the names in this code to use capital letters. In Go, capitalizing the name of a function or type exports the type from the package. Doing so is not technically necessary here, because Test.go (which contains the type) and TestTestRunner.go (which contains the test, and has the best name I could think of, as confusing as it might be to read) exist in the same package. It is likely that we’ll want to export this type in the future, along with its methods and constructor, so I opted to pre-emptively export them now, when changing the names is still simple to do without refactoring tools.

Next time, we want to further refactor this code to invoke the test method dynamically. See you then!


Thanks for reading,

Alec