On Unit Tests
I think I am coming around to appreciating the value of unit tests. I used to dismiss the practice, because I thought too many developers are invested more into writing unit tests than getting any real work done — and also I never really used any proper unit testing framework, only ad-hoc testing throw-away code that would test this one thing here, that other thing there and that’s that, and only once, never really would run it again to see if results were the same.
I came across Google’s Unit Test framework, after hearing about it on a CppCon video, or maybe it was somewhere else, and I thought it looked reasonably nice, so I decided to try it someday — and try it I did, and gradually it changed my perspective on the matter completely.
We now have two main unit tests, one for our core library(Switch), and for CloudDS (our distributed datastore), and that’s pretty much only the beginning. We are going to add more tests and extend coverage to other codebases.
It just feels so good, knowing that those unit tests have your back. If any changes affected anything in unintended ways, those unit tests will catch those problems in time. That’s a very powerful safety system.
Here’s a very simple unit test, from our Switch’s unit tests:
TEST(Buffer, Basics)
{
IOBuffer a(_S("hello")), b, c;
EXPECT_EQ(a.length(), STRLEN("hello"));
EXPECT_EQ(b.length(), 0);
a.SetPosition(2);
EXPECT_EQ(a.Position(), 2);
std::swap(a, b);
EXPECT_EQ(b.Position(), 2);
EXPECT_EQ(a.Position(), 0);
EXPECT_EQ(b.length(), STRLEN("hello"));
EXPECT_EQ(a.length(), 0);
c = b;
EXPECT_EQ(c.Position(), b.Position());
EXPECT_EQ(c.length(), STRLEN("hello"));
EXPECT_TRUE(c.AsS32().Eq(_S("hello")));
c.SetPosition(1);
IOBuffer foo(std::move(c));
EXPECT_EQ(foo.Position(), 1);
EXPECT_EQ(foo.length(), STRLEN("hello"));
EXPECT_TRUE(foo.AsS32().Eq(_S("hello")));
}
This is for basic Buffer(a string class) operations.