0

I am trying to write a JUnit Test Case for the below Java Code:

private java.lang.Object __equalsCalc = null;

public synchronized boolean equals(java.lang.Object obj) {

    if (!(obj instanceof Crop)) 
        return false;
    Crop other = (Crop) obj;
    if (obj == null) return false;
    if (this == obj) return true;
    if (__equalsCalc != null) {
        return (__equalsCalc == obj);
    }
}

The Test case i wote is below:

public void testCrop() {
    Crop cp = new Crop();

    Object obj = false;

    cp.equals(obj);
    assertSame(obj instanceof Crop, false);

}


public void testCrop1() {

    Crop other = (Crop) obj;
    // assertSame(other.equals(obj), true);
    assertEquals(obj, other);
}

The test case for instanceof is working fine, but while checking if(obj == null) return false; the test case is failing:

Screenshot

Jeff Olson
  • 6,323
  • 2
  • 22
  • 26
user1824878
  • 1
  • 1
  • 2
  • Please clarify your question. How is `obj` defined? What is the failure message of the test? Side notes: using assertSame to test boolean values is not very clean. Use assertTrue() and assertFalse(). There is no need to test for null when you have already tested for instanceof. null is not an instanceof anything. But the most important is: To test the equals method of your class, you should at least call it in the test and verify if the result is what you expect. You don't do that in your tests. – JB Nizet May 10 '13 at 14:32
  • private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof Crop)) return false; Crop other = (Crop) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } – user1824878 May 10 '13 at 15:25
  • the test is pass but when i try to code coverage it shows the passed lines in red.(which means not covered). – user1824878 May 10 '13 at 15:27
  • Well null isn't an instance of Crop is it! Swap the if statements round. Clearer question would have helped. – Tony Hopkinson May 10 '13 at 21:20

2 Answers2

0

You could use assertFalse

public void testEqualsNullIsFalse() {
    Crop crop = new Crop();

    assertFalse(crop.equals(null));
}
Marco Forberg
  • 2,634
  • 5
  • 22
  • 33
0

Test case has to be something like

Crop cp = new Crop();
Object obj = null;

bool expected = false;

assertEquals(expected,cp.equals(obj));

NB if you are trying do something like the as operator, have a look at this

how to emulate as operator in Java

Community
  • 1
  • 1
Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39