stmt if(obj == null)的JUnit测试用例返回false;

时间:2013-05-10 14:08:40

标签: object junit null

我正在尝试为下面的Java代码编写一个JUnit测试用例:

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);
    }
}

我测试的测试案例如下:

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);
}

instanceof的测试用例运行正常,但在检查if(obj == null) return false;时,测试用例失败了:

Screenshot

2 个答案:

答案 0 :(得分:0)

您可以使用assertFalse

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

    assertFalse(crop.equals(null));
}

答案 1 :(得分:0)

测试用例必须类似于

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

bool expected = false;

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

注意如果您尝试执行as运算符之类的操作,请查看此

how to emulate as operator in Java