Are closing brackets counted as statements in Statement Coverage? What about if they come after a return statement?

417 views Asked by At

I'm doing a simple assignment where I have to go over test case coverage(statement coverage, path coverage, etc) of a function.

I've tried endlessly to add code here and StackOverflow won't accept it no matter how I format it, so I'll just explain a very simple example.

Let's say you get to an if statement that has a return statement inside it. In the line below the return line is the if's closing bracket '}'

My professor and our textbook have been pretty vague about what a statement is, but my understanding is that for a line of code to be a statement it has to perform some type of function such as assigning a value to a variable or being a conditional statement like an if or while loop.

So my questions are:

  • Does the closing bracket count as a statement? Or do they only count as a line?
  • When the computer is reading the code and hits the return statement, does it jump to the correct number of closing brackets before leaving the function and returning a value?
1

There are 1 answers

4
Ira Baxter On

Closing brackets are not traditionally counted as statements.

Even if they follow a return (or any other kind of unconditional control transfer, e.g. goto to raise exception.).

A more interesting case is:

  if (...) {
          return;
          x=1;
   }

The x=1; statement can't get control. Test coverage should tell you it is uncovered because it never gets executed.

This example is exactly the same code, slightly reformatted:

  if (...) { 
       return; x=1; }

Many test coverage tools will show you covered lines rather than covered code, so would mark the return line as covered. That's wrong; x=1; is still uncovered and the coverage display tool should make that clear.

This is especially important if you have a long source line which exits (e.g., by exception) in the middle:

x=foo().bar().baz();

If bar() throws an exception, then foo(). is covered, x=... is not, and baz() is not. This shows why line coverage, while common, can be very misleading.

Now consider this case:

if (a) {
     ...
     if (b)
        return;
}
c; 

If a and b are true, the return statement executes. Control doesn't flow past the if (b) statement. If a is true and b is false... the return isn't executed and control flows past the if (b) to statement c;. In this case you can argue the } is "covered" even though it isn't a statement. A good coverage tool should show } c; as covered.