简体   繁体   English

使用JUnit和Mockito测试方法以增强分支覆盖率

[英]Testing a method with JUnit and Mockito to enhance branch coverage

I am writing a JUnit to enhance the line and branch coverage of a method. 我正在编写一个JUnit以增强方法的行和分支覆盖范围。 There is only one line left in method under test that I am trying to cover but somehow it is not being covered. 我正在尝试覆盖的测试方法中只剩下一行,但不知何故没有覆盖。 I've tried to use Mockito to make it simpler but still if( o != null ) comes as red in Cobertura Report. 我尝试使用Mockito使其更简单,但是在Cobertura Report中if( o != null )仍然是红色。

Method under test: 被测方法:

public String handleParams( Map<String, Object> params ) {
    StringBuilder sb = new StringBuilder();

    if( params != null ) {
        Set<String> keys = params.keySet();
        for( String s : keys ) {
            Object o = params.get( s );
            if( o != null ) {
                if( sb.length() > 0 ) {
                    sb.append("," );
                }
                sb.append( s + "-" + o.toString() );
            }
        }
    }

    return sb.toString();
}

JUnit test: JUnit测试:

@Test
public void testHandleParams() throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put("Object1", new Object());
    params.put("Object2", new Object());

    TestWSAuditHandler handler = new TestWSAuditHandler();
    String handle = handler.handleParams(params);

    assertNotNull(params);
    assertEquals(2, params.size());
    assertTrue(handle instanceof String);

    // Null Condition
    params = null;

    handler = new TestWSAuditHandler();
    handle = handler.handleParams(params);

    assertNull(params);
    assertEquals(null, params);
    assertTrue(handle instanceof String);

    // Mocking params
    params = Mockito.mock(Map.class);
    Mockito.when(params.get(Mockito.anyString())).thenReturn(null);

    handler = new TestWSAuditHandler();
    handle = handler.handleParams(params);
}

Want to know how will I make o == null 想知道我将如何使o == null

Thanks in advance 提前致谢

How about: 怎么样:

params.put("Object3", null);

before your call to handleParams ? 在您致电handleParams之前?

This way, when you will call params.get("Object3") in handleParams , you will get the value associated to the key Object3 , which in this case is null . 这样,当您在handleParams调用params.get("Object3")时,您将获得与键Object3关联的值,在这种情况下为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM