如何使用JUnit在Java中使用布尔返回类型测试方法

时间:2016-05-11 17:26:55

标签: java unit-testing junit cobertura

我正在编写一个JUnit测试用例,用于获取Line和Branch覆盖率的方法。正在测试的方法调用另一种Boolean类型的方法,我无法覆盖该部分,因为在Cobertura报告中,以下行显示为红色。

if (getLoggingHandler().isGeneralDebugEnabled())

待测方法:

public void logMethodEndDebug(ILoggable l, String c, String m, String msg, Object... args) {

    if (getLoggingHandler().isGeneralDebugEnabled()) {
        String cf = ComponentUtils.createControlFrag(l, c);
        StringBuilder sb = new StringBuilder(cf);
        sb.append(m + StringConstants.SPACE + LogConstants.END);
        sb.append(StringConstants.BRACE_OPEN + String.format(msg, args) + StringConstants.BRACE_CLOSE);
        getLoggingHandler().handleGeneralDebug(sb.toString());
    }

}

JUnit测试:

@Test
public void testLogMethodStartDebug() throws Exception {
    String var1 = "var1";
    String var2 = "var2";
    String var3 = "var3";
    Object[] object = new Object[] {"var4"}; 

    BaseComponent baseComponent = new BaseComponent();
    baseComponent.setLoggingHandler(new TestLoggingHandler());

    ILoggable loggable = new ServiceContext();

    baseComponent.logMethodEndDebug(loggable, var1, var2, var3, object);

    assertTrue(baseComponent.getLoggingHandler().isGeneralDebugEnabled());
}

有没有办法覆盖这个getLoggingHandler().isGeneralDebugEnabled()

谢谢,

1 个答案:

答案 0 :(得分:4)

您可以定义模拟,然后强制该值在调用getLoggingHandler().isGeneralDebugEnabled()时返回true

以下是代码中的内容:

@Mock
private TestLoggingHandler mockLoggingHandler;

...

@Test
public void testLogMethodStartDebug() throws Exception {
    String var1 = "var1";
    String var2 = "var2";
    String var3 = "var3";
    Object[] object = new Object[] {"var4"}; 

    when(mockLoggingHandler.isGeneralDebugEnabled()).thenReturn(true);

    BaseComponent baseComponent = new BaseComponent();
    baseComponent.setLoggingHandler(mockLoggingHandler);

    ILoggable loggable = new ServiceContext();

    baseComponent.logMethodEndDebug(loggable, var1, var2, var3, object);

    assertTrue(baseComponent.getLoggingHandler().isGeneralDebugEnabled());
}

或者,如果generalDebugEnabled的setter可用,您可以执行以下操作:

@Test
public void testLogMethodStartDebug() throws Exception {
    String var1 = "var1";
    String var2 = "var2";
    String var3 = "var3";
    Object[] object = new Object[] {"var4"}; 

    BaseComponent baseComponent = new BaseComponent();
    baseComponent.setLoggingHandler(new TestLoggingHandler());
    baseComponent.getLoggingHandler().setGeneralDebugEnabled(true);

    ILoggable loggable = new ServiceContext();

    baseComponent.logMethodEndDebug(loggable, var1, var2, var3, object);

    assertTrue(baseComponent.getLoggingHandler().isGeneralDebugEnabled());
}