Mastering Unit Testing Using Mockito and JUnit by Sujoy Acharya

Mastering Unit Testing Using Mockito and JUnit by Sujoy Acharya

Author:Sujoy Acharya [Acharya, Sujoy]
Language: eng
Format: azw3, mobi, epub, pdf
Publisher: Packt Publishing
Published: 2014-07-14T16:00:00+00:00


Learning the inner details of code instrumentation

Coverage is measured by the ratio of basic code branches or instructions that were exercised by some tests to the total number of instructions or branches available in the system under test.

The ratio is measured in a series of steps. First, in a copy of source code, each block of statement is instrumented with an accumulator flag. Then, the tests run on the instrumented code and update the flags. Finally, a program collects the accumulator flags and measures the ratio of the flags turned on versus the total number of flags. Bytecode can be changed on the fly or during compilation. This is actually what test coverage frameworks do under the covers.

Two code instrumentation options are available: source code instrumentation and object code instrumentation. Object code instrumentation modifies the generated bytecode, so it is hard to implement.

The preceding code coverage example has seven lines, but if we expand the branches into lines, then it will result in 14 lines. If a coverage tool needs to instrument the code, then it will modify the source code and initialize an array of length 14 with 0 and set 1 when a line is executed while a test is being run. The following example demonstrates the source code instrumentation:

int[] visitedLines = new int[14]; public int absSumModified(Integer op1 , Integer op2) { visitedLines[0] = 1; if(op1 == null) { visitedLines[1] = 1; if(op2 == null) { visitedLines[2] = 1; return 0; }else { visitedLines[3] = 1; } }else { visitedLines[4] = 1; } visitedLines[5] = 1; if(op1 == null) { visitedLines[6] = 1; if(op2 != null) { visitedLines[7] = 1; return Math.abs(op2); }else { visitedLines[8] = 1; } }else { visitedLines[9] = 1; } visitedLines[10] = 1; if(op2 == null) { visitedLines[11] = 1; return Math.abs(op1); }else { visitedLines[12] = 1; } visitedLines[13] = 1; return Math.abs(op1)+Math.abs(op2); }}



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.