Yousuf Yousuf - 6 months ago 11
Java Question

How to test a Boolean with JUnit

I am writing a

JUnit
test case for a method to get a Line and Branch coverage. Method under test invokes another method of type
Boolean
and I am unable to cover that part because on the
Cobertura
report the following line shows red.

if (getLoggingHandler().isGeneralDebugEnabled())


Method under test:

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:

@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());
}


Is there any way to cover this
getLoggingHandler().isGeneralDebugEnabled()
?

Thanks,

Answer

You can define a mock and then force the value to return true when getLoggingHandler().isGeneralDebugEnabled() is called

Here is what that would look like in code:

@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());
}

Alternately, if the setter for generalDebugEnabled is available you could do something like:

@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());
}