提问者:小点点

如何在junit的catch子句中覆盖我的日志记录器


我正在尝试对我的应用程序进行完整的 junit 测试,但在测试记录器消息时我陷入困境。

try {
    fillParameters(args);
} catch (ArgumentException e) {
    logger.error(e.getMessage(), e);
    return;
}

这是触发异常的代码:

if (args.length > 3) {
    throw new ArgumentException("Wrong use of the command -> too many args"); 
}

一个测试:

@Test
public void testFillParametersWithTooManyArguments() {
    String[] args = { "...", "...", "...", "..." };
    Throwable e = null;
    try {
        testInstance.fillParameters(args);
    } catch (Throwable ex) {
        e = ex;
    }
    assertTrue(e instanceof ArgumentException); //this test is working as expected
}

当我查看代码覆盖率时,logger.error(e.getMessage(),e);部分未覆盖,我该如何覆盖?我想我一定要嘲笑那个伐木工人?


共1个答案

匿名用户

简答题 测试
您实际要测试的代码。

一些信息 第一个代码块中的代码绝不
是由示例单元测试中的代码测试的。我假设因为它看起来像 Java 代码并且问题被标记为 Java 问题,第一个代码块中的代码实际上在某个地方的方法中。您必须将该方法组合在一起,才能在该方法的异常捕获块中获取测试覆盖率。

例如:

public void IHateToTellPeopleMyMethodName(final String[] args)
{
    try
    {
        fillParameters(args);
    }
    catch (ArgumentException e)
    {
        logger.error(e.getMessage(), e);
        return;
    }
}

为了获得< code > ihatetotellpeonpelmymethodname 方法中catch块的测试覆盖率,必须在单元测试中测试< code > ihatetotellpeonpelmymethodname 方法。

此单元测试方法对测试IHateToTellPeopleMyMethodName方法没有任何作用,因为它不调用ihateToTell PeopleMyMethodName

@Test
public void testThatInNoWayTestsTheIHateToTellPeopleMyMethodNameMethod()
{
    String[] args = { "...", "...", "...", "..." };

    try
        {
        testInstance.fillParameters(args);
                fail("expected exception not thrown");
    }
        catch (Throwable ex)
        {
            assertTrue(e instanceof ArgumentException);
    }
}

与上面的单元测试代码不同,此单元测试涵盖了 IHateToTellPeopleMyMethodName 方法。

@Test
public void testTheIHateToTellPeopleMyMethodNameMethod()
{
    String[] args = { "...", "...", "...", "..." };

    testInstance.IHateToTellPeopleMyMethodName(args);

          verify(mockLogger).error(
                eq(EXPECTED_MESSAGE_TEXT),
                    any(ArgumentException.class));
}

编辑注释
我的错,any() 需要一个类对象作为参数,而不是名。