我为一个返回String的私有函数编写了一个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);
}
我还有一个函数返回boolean但这不起作用。
但是因为我收到编译时错误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 :(得分:4)
我完全反对孤立地测试私有方法。单元测试应该针对类的公共接口进行(因此无意中测试私有方法),因为这是在生产环境中处理它的方式。
我认为在某些小案例中你想要测试私有方法,并且使用这种方法可能是正确的,但是当我遇到我想要测试的私有方法时,我当然不会放下所有冗余代码。
答案 1 :(得分:0)
返回值将被“自动装箱”到布尔对象。由于基元不能为空,因此不能对null进行测试。由于Autoboxing,不能调用.booleanValue()。
但我和@ 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;
}
}
}