2012-03-27 56 views
1

我已经为返回String的私有函数编写了JUnit。 它工作正常。如何写一个返回布尔值的私有函数的JUNIT?

public void test2() throws Exception 
    { 
    MyHandler handler = new MyHandler(); 
    Method privateStringMethod = MyHandler.class.getDeclaredMethod("getName", String.class); 
    privateStringMethod.setAccessible(true); 
    String s = (String) privateStringMethod.invoke(handler, 852l); 
    assertNotNull(s); 
    } 

我有一个函数返回布尔值,但这是行不通的。 但是,我得到一个编译时错误说Cannot cast from Object to boolean.

public void test1() throws Exception 
    { 
     MyHandler handler = new MyHandler(); 
     Method privateStringMethod = MyHandler.class.getDeclaredMethod("isvalid", Long.class); 
     privateStringMethod.setAccessible(true); 
     boolean s = (boolean) privateStringMethod.invoke(handler, 852l); 
     assertNotNull(s); 
    } 

如何运行

+0

不isValid()的返回** **布尔**或**布尔? – Jim 2012-03-27 10:51:35

+0

@Jim它返回布尔值。 – vikiiii 2012-03-27 10:53:40

回答

0

返回值将被自动装箱到一个布尔对象。由于基元不能为空,因此不能针对null进行测试。即使.booleanValue()也不能被调用,因为Autoboxing。

但我与@ alex.p的观点相同,关于测试私有方法。

public class Snippet { 

@Test 
public void test1() throws Exception { 
    final MyHandler handler = new MyHandler(); 
    final Method privateStringMethod = MyHandler.class.getDeclaredMethod("isvalid"); 
    privateStringMethod.setAccessible(true); 
    final Boolean s = (Boolean) privateStringMethod.invoke(handler); 
    Assert.assertTrue(s.booleanValue()); 
} 

class MyHandler { 
    private boolean isvalid() { 
     return false; 
    } 
} 

}

4

我完全反对在隔离测试私有方法。单元测试应该针对该类的公共接口(因此无意测试私有方法)进行,因为这是在生产环境中如何处理的。

我想有小的情况下,你想测试私有方法,使用这种方法可能是正确的,但我肯定不会放下所有冗余代码,只要我碰到一个我想测试的私有方法。