我正在编写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
提前致谢
答案 0 :(得分:1)
怎么样:
params.put("Object3", null);
在致电handleParams
之前?
这样,当您在params.get("Object3")
中拨打handleParams
时,您将获得与密钥Object3
相关联的值,在这种情况下为null
。