Junit check for boolean method

I have a problem writing a test case for this method below: EvenNum(double)

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

This is a test file that I wrote, but I think I have an inheritance problem or a logical problem in this case. It should be very simple, but can not understand. Here is the code I wrote:

 import static org.junit.Assert.*; import org.junit.Test; public class OddEvenTest { @Test public void testEvenNum() { boolean ans = true; boolean val; double num= 6; val = OddEven.EvenNum(num) // cant inherit the method dont know why??? assertEquals(ans,val); } } 
+4
source share
3 answers

Two things:

  • You are invoking a non-static method statically. The method must be declared static:

    public static boolean evenNum (double num) {
    ,,,}

  • You have spelled the method name incorrectly. Look carefully. Also consider renaming it to something more readable, like isEven(...)

+4
source

You have a number of problems:

  • you are trying to call a static static method
  • java method names are case sensitive and you have mixed up this thing.

I fixed some things for you and just checked 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 that System.out.println() calls in OddEven strictly for debugging, all of this can be collapsed 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)); } } 

Now the code is shorter, and unit test is even an odd case for good measure.

+4
source

It is like testing is crazy and programming is crazy. The whole method is computing num% 2 == 0. You can simply specify the code that is required everywhere and throw away both the method and its tests. If you must support the method, it relies on mathematical identity, you do not need to verify them. You can also check 1 + 1 == 2.

0
source

All Articles