1

我为返回字符串的私有函数编写了一个 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);
}

我怎么能跑?

4

2 回答 2

4

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

我想在一些小情况下你想测试私有方法并且使用这种方法可能是正确的,但是当我遇到我想要测试的私有方法时,我当然不会放下所有多余的代码。

于 2012-03-27T10:46:07.060 回答
0

返回值将被“自动装箱”为布尔对象。由于原语不能为 null,因此您不能针对 null 进行测试。由于自动装箱,甚至不能调用 .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;
        }
    }
}
于 2012-03-27T11:11:03.730 回答