【问题标题】:How can I write a JUnit test of a private function which is returning a Boolean?如何编写返回布尔值的私有函数的 JUnit 测试?
【发布时间】:2012-03-27 10:30:51
【问题描述】:

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

我怎么跑?

【问题讨论】:

  • isvalid() 是返回 boolean 还是 Boolean
  • @Jim 它返回布尔值。

标签: java private junit3


【解决方案1】:

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

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

【讨论】:

  • 这如何回答这个问题?
【解决方案2】:

返回值将被“自动装箱”为布尔对象。由于原语不能为 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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-12
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 2018-04-09
    • 1970-01-01
    相关资源
    最近更新 更多