Junit testing for a boolean method

后端 未结 3 1756
一个人的身影
一个人的身影 2021-01-12 02:11

I have problem writing a testcase to this method below: EvenNum(double)

public class OddEven {

/**
 * @param args
 */

public boolean evenNum(d         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-12 02:25

    You have a number of issues:

    • you are attempting to call a non-static method statically
    • method names in java are case sensitive and you've mixed up the case.

    I corrected some things for you and just verified the code below:

    OddEven.java:

    public class OddEven {
    
            public boolean evenNum(double num)
            {
                if(num%2 == 0)
                {
                    System.out.print(true);
                    return true;
                }
                else
                {
                    System.out.print(false);
                    return false;
                }
    
            }
    }
    

    OddEvenTest.java

    import static org.junit.Assert.*;
    import org.junit.Test;
    
    public class OddEvenTest {
    
        @Test
        public void testEvenNum() {
            boolean ans = true;
            boolean val;
            double num = 6;
            OddEven oddEven = new OddEven();
    
            val = oddEven.evenNum(num);
            assertEquals(ans,val);
        }
    
    }
    

    Assuming the calls to System.out.println() in OddEven are strictly for debugging, the whole thing could be collapsed down to:

    OddEven.java

    public class OddEven {
        public boolean evenNum(double num) {
            return num%2 == 0;
        }
    }
    

    OddEvenTest.java

    import static org.junit.Assert.*;
    import org.junit.Test;
    
    public class OddEvenTest {
    
        @Test
        public void testEvenNum() {
            OddEven oddEven = new OddEven();
            assertTrue(oddEven.evenNum(6));
            assertFalse(oddEven.evenNum(5));
        }
    }
    

    The code is now shorter and the unit test even covers an odd case for good measure.

提交回复
热议问题