Anghel Alexandru
Anghel Alexandru

Reputation: 39

Junit test run freezes

Today was my first contact with Junit so i had a little practice with some programs that return ints and it worked ok. Then i wanted to try to return a boolean and when i run the test case , it doesn't do anything, it's running but the bar doesn't turn green or red.

this is the class:

public class primcheck {

    public boolean prim(int n) {
        int nr=0;
        int i;
        while(nr==0) {
            for(i=2;i<=n/2;i++) {
                if(n%i==0) nr++;
            }

        }
        if(nr==0) return true;
         return false;


    }       
}

and the Junit test case

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class primeTest {

    @Test
    void test() {
        primcheck pc = new primcheck();
        boolean output = pc.prim(5);
        assertEquals(false,output);
    }

}

Can you please explain to me what i did wrong? Thank you in advance !

Upvotes: 0

Views: 1750

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

The problem is nothing to do with JUnit. You'd have the same problem if you ran it "by hand".

    int nr=0;
    int i;
    while(nr==0) {
        for(i=2;i<=n/2;i++) {
            if(n%i==0) nr++;
        }

    }

If you never find a factor with the innermost if, you will just keep on looping indefinitely, because nothing makes nr==0 false: after executing the for loop once, you just keep on running the while loop without executing the for loop body.

Remove the while loop, and add the condition to the for loop guard (or just omit it entirely):

        for(i=2;i<=n/2 && nr==0;i++) {

Upvotes: 1

Related Questions