Sampath
Sampath

Reputation: 1202

Should there be at least one assert in a unit test? If so, why?

If we take for example gtest, we have the option to use asserts like ASSERT_NE or checks like EXPECT_NE. One of my colleagues pointed out that I should have at least one assert in my test preferably the condition which checks the main objective. So, far I was used to using ASSERTs in places where the continuation of test is useless, and EXPECTs in places where the test could continue. What is the correct way of using ASSERTs and EXPECTs?

Upvotes: 0

Views: 119

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22211

The main difference between EXPECT_* and ASSERT_* macros is that assertions stop the test immediately if it failed, while expectations allow it to continue.

Here's what GoogleTest Primer says about it:

Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

So, to illustrate it:

TEST_F(myTest, test1)
{
    uut.doSomething();
    ASSERT_EQ(uut.field1, expectedvalue1);
    ASSERT_EQ(uut.field2, expectedvalue2);
}

If field1 doesn't match assertion, test fails and you have no idea if field2 is correct or not. This makes debugging much more difficult.

Choice between these options is mostly matter of agreement in your team, but I'd stick to GTest proposition of using EXPECT_* as the backbone of all checks and ASSERT_* only if you test something crucial to continue, without which further part of test doesn't make any sense (for example, if your unit under test was not created correctly).

Upvotes: 2

Related Questions