When I'm writing unit-tests, I generally try to pre-empt mistakes I (or perhaps another developer) is likely to come along and make.
Take this class Foo
for example, which has an equality-operator:
struct Foo {
int m_foo;
bool operator==(const Foo& other) const {
return m_foo == other.m_foo;
}
};
// test code
TEST(FooEquality, Equal) {
Foo f1, f2;
f1.m_foo = 1;
f2.m_foo = 1;
EXPECT_EQ(f1, f2);
}
TEST(FooEquality, NotEqual) {
Foo f1, f2;
f1.m_foo = 1
f2.m_foo = 2;
EXPECT_NE(f1, f2);
}
A simple but likely problem: future me adds a new member variable m_bar
and forgets to update the equality operator.
struct Foo {
int m_foo;
int m_bar;
bool operator==(const Foo& other) const {
// BUG: We didn't check m_bar, but tests still pass!
return m_foo == other.m_foo;
}
};
Is there a clean way of writing a test for this?