Should I unit test expected assertions?

231 Views Asked by At

I'm doing some unit testing for C in CUnit. I have some pre-conditions for an insert function that states that some buffert parameters shouldn't exceed a certain buffer size. In the insert function I have made some asserts to defend against this. Now, should I make a unit test for these expected assertions?

db.c:

  #define BUFFER_SIZE 128

  ...

  Node *delete(char *key, char *buffer_msg, Node *root) {
        assert(sizeof(key) <= BUFFER_SIZE);
        assert(sizeof(buffer_msg) <= BUFFER_SIZE);
        assert(root != NULL);

        ...
  }

test_db.c:

  void test_delete_buffer_size_should_cast_assertion(void){
        if (NULL != fileDb) {
              //Arrange
              char *key = "Test";
              char buffer_msg[129];
              Node *database = NULL;     

              //Act
              database = create_db(fileDb);

              //Assert
              CU_ASSERT(delete(key, buffer_msg, database)); <-- ???

              //Clean up
              free(database);
              database = NULL;
       }
  }
2

There are 2 best solutions below

0
On

To test or not to test assertions ...

When testing delete(), say unit tests do not test the assertions yet the assertion is coded wrong. When does this error get discovered - during a higher level test? That defeats unit testing.

assert(sizeof(buffer_msg) >= BUFFER_SIZE);  // incorrect assertion
assert(sizeof(buffer_msg) >  BUFFER_SIZE);  // correct assertion

Recommend testing assertions at unit test.

0
On

Unit test ideally should test the core functionality of the function/API. Testing assertions in not required because it is not modifiable in the scope of your method.

This is very similar to usage of any other third party dependency within core business logic. Such cases could however be covered in integration tests,but not within unit tests.