简体   繁体   中英

JUnit Testing: How To Test If Statements Without Missing A Branch?

I have run EclEmma for coverage on my JUnit Test Cases and have reached up to 100% on some. However, on the ones that are 82% or 95% covered, there is a message next to my code that says "1 of 2 branches missed" and I can't seem to solve this issue.

After looking over my classes, I noticed that this message only appears next to my if-statements, and that is what's keeping my tests from being 100% covered.

I guess I'm asking if anyone knows how to test an if-statement in JUnit, so that neither branch is missed.

This is the code I'm trying to test:

private double height;
    public void setHeight(double height){
        if(height <=0){
            this.height = 0;
        }
        else{
            this.height = height;
        }
    }//method close

( I am using JUnit 4 )

Simple:

you want to have one distinct test case per path within your method under test; like:

  • testSetHeightWithNegativeValue()
  • testSetHeightWithZeroValue()
  • testSetHeightWithPositiveValue

Each of them gives specific input to your method under test and checks for the expected output.

Where the real take away here is: consider thinking about your code. You should not need a coverage tool to figure that you need more tests for your method. Instead: you look at your method, and think what it is doing; and then you write testcases.

Coverage is fine to tell you that you did the right thing; but "doing the right thing" is what you should strive to do by yourself; and not to meet some numbers.

And, as the comments point out: consider using the TDD approach: when you write your tests before you create the "matching" piece of production code, then you make that "thinking" part an essential element of your working procedure.

Your code

public void setHeight(double height){
    if(height <=0){
        this.height = 0;
    }
    else{
        this.height = height;
    }
}

has two possible branches:

height <= 0

public void setHeight(double height){
     this.height = 0;
}

height > 0

public void setHeight(double height){
    this.height = height;
}

So in if statement, you can go to one statement or another in else . You have to create two unit tests to cover all possible ways - one for parameter passed height > 0 and second for height <= 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM