Yasser CHENIK
Yasser CHENIK

Reputation: 407

How to know what instructions I did/didn't execute at the end of my test in JUnit

I m decent java developer but I don't know a lot about testing frameworks. I just created this a simple method :

public static String signOf(String str) {//expects a number as String and gives you the sing of it (positive or negative)
    int number = 0;
    str = str.trim();
    try {
        number = Integer.parseInt(str);
    } catch (Exception e) {
        return "NaN";
    }

    if (str.equals("0")) {
        return "positive and negative";
    }
    if(str.length()==count(number)){
            return "positive";
    }
    if(str.length()==(count(number)+1)){
        if (str.charAt(0) == '+') {
            return "positive";
        }
        if (str.charAt(0) == '-') {
            return "negative";
        }
    }
     return "NaN" ;
}

And to test it I created this other method ( I use IntelliJ as IDE) :

@Test
public void testSignOf(){
    assertEquals("positive and negative",signOf("0"),"0 is positive and negative at the same time.");

    assertEquals("positive",signOf("19"),"19 is positive.");

    assertEquals("negative",signOf("-0"),"-0 is negative.");
    assertEquals("positive",signOf("+0"),"+0 is positive.");

    assertEquals("negative",signOf("-12"),"-12 is negative.");
    assertEquals("positive",signOf("+23"),"+23 is positive.");

    assertEquals("NaN",signOf("1-1"),"1-1 is NaN.");
    assertEquals("NaN",signOf("ad"),"ad is NaN.");
    assertEquals("NaN",signOf("-"),"- is NaN.");
    assertEquals("NaN",signOf("+"),"+ is NaN.");
    assertEquals("NaN",signOf("+-"),"+- is NaN.");
    assertEquals("NaN",signOf("--1"),"--1 is NaN.");
}

Is there any way to know if my test entered every instruction of my code and every possible case. Normally at the end of the test it goes green if everything went as expected. But it doesn't notify you if you didn't or did visit a certain instruction after an if statement, in the method you tested.
This testing reminds me of this deep thought :

What I know is little.
What I know that I don't know is big.
But what I don't know that I don't know is A lot bigger.


Rest of the code :

public static int  count(int num){
    if (num==0) return 1;//Btw the test helped me to add this if 
    int count = 0;
    while (num != 0) {
        // num = num/10
        num /= 10;
        ++count;
    }
    return count ;
}

Upvotes: 1

Views: 78

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96385

If you want to know what lines of code got executed, that is what code coverage tools are for. Intelliij comes with a code coverage plug-in, you can run your test with code coverage and it will tell you which lines are covered and which aren't. See https://www.jetbrains.com/help/idea/running-test-with-coverage.html

Upvotes: 2

Related Questions