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

时间:2016-05-17 15:10:29

标签: java junit mockito cobertura

我正在编写JUnit来增强方法的行和分支覆盖率。在我试图覆盖的测试方法中只剩下一条线,但不知何故它没有被覆盖。我尝试使用Mockito使其更简单,但if( o != null )报告中Cobertura仍为红色。

待测方法:

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

想知道如何制作o == null

提前致谢

1 个答案:

答案 0 :(得分:1)

怎么样:

params.put("Object3", null);
在致电handleParams之前

这样,当您在params.get("Object3")中拨打handleParams时,您将获得与密钥Object3相关联的值,在这种情况下为null