JUnit – missing branch when using asserttrue instead of assertNull

In Java / JUnit, I need to test null with some objects There are many ways to test a condition, but I've been using asserttrue for most of the tests When I check null in asserttrue, EclEmma declares that it is only testing a branch

When I manually parse a statement into a variable (such as setting the result to a Boolean value and passing it to asserttrue), code coverage is considered to be completed on the assertion rather than the variable initialization line

Why is that? Is this related to the extra bytecode explicitly mentioned in Java? Any solution (except using other assert statements)

assertTrue:

assertTrue( myObject == null ); //1 of 2 branches

assertTrue:

boolean test = (myObject == null); //1 of 2 branches missing
assertTrue(test); // complete

assertNull:

assertNull( myObject ) //complete;

Solution

For most Boolean expressions, the java compiler generates additional branches in bytecode

In your code, the Boolean expression you use is MyObject = = null

To calculate this value, the java compiler generates two parameters on the code push stack, and then makes a conditional jump to push 1 (true) or 0 (false) on the stack Jacoco reported branch coverage for this conditional jump

Therefore, using the fact that MyObject = = null triggers the behavior you describe

As other examples, try:

boolean t = true;
boolean f = false;
boolean result1 = (t && f) || f; // 3 out of 6 missed.
boolean result2 = !t;            // 1 out of 2 missed.

If a Boolean expression is returned by a function, for example, it may be useful to use it as a condition in if then else statements elsewhere Although the way the java compiler works is primarily a consequence, it helps to evaluate the conditional coverage (not just branch coverage) of the original java code

This function is not well documented, but here are some pointers:

> JaCoCo test cases for Boolean Expressions > JaCoCo forum discussion on branches generated for the statement a = ! A does anyone have more pointers to documents?

Therefore, it is actually related to additional byte code, rather than specific examples of synthetic byte compiler construction for filtering options

Note: since the initial answer, the main edit is too much speculation Thank @ IRA Baxter for the good & critical discussion

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>