We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Tests

By now, you should be familiar enough with unit testing. Like anything, the more you do it, the better you will be at it. More importantly, you will begin to understand how to write code that is easier to test.

We'll use TDD for this part, and Go's testing package.

If you're unsure how to write unit tests in Go, I highly recommend reading Dave Cheney's excellent blog post on the subject.

Assignment

The purpose of this function will be to split the user's input into "words" based on whitespace. It should also lowercase the input and trim any leading or trailing whitespace. For example:

  • hello world -> ["hello", "world"]
  • Charmander Bulbasaur PIKACHU -> ["charmander", "bulbasaur", "pikachu"]

All tests go inside TestXXX functions that take a *testing.T argument:

func TestCleanInput(t *testing.T) {
    // ...
}

Remember to import the testing package if it isn't imported already.

I like to start by creating a slice of test case structs, in this case:

cases := []struct {
	input    string
	expected []string
}{
	{
		input:    "  hello  world  ",
		expected: []string{"hello", "world"},
	},
	// add more cases here
}

Then I loop over the cases and run the tests:

for _, c := range cases {
	actual := cleanInput(c.input)
	// Check the length of the actual slice
	// if they don't match, use t.Errorf and continue to the next case
	if len(actual) != len(c.expected) {
		// error and continue here
	}
	for i := range actual {
		word := actual[i]
		expectedWord := c.expected[i]
		// Check each word in the slice
		// if they don't match, use t.Errorf to print an error message
		// and fail the test
	}
}

Run and submit the CLI tests.