gpt4 book ai didi

java - 如何使用 JUnit 在 Java 中测试具有 boolean 返回类型的方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:17 24 4
gpt4 key购买 nike

我正在编写一个 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()

谢谢,

最佳答案

您可以定义一个模拟,然后在调用 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());
}

关于java - 如何使用 JUnit 在 Java 中测试具有 boolean 返回类型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37169485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com