我正在编写一个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
==空
提前感谢
怎么样:
params.put("Object3", null);
在呼叫handleParams
之前?
这样,当您在handleParams
中调用params.get("Object3")
时,您将获得与密钥Object3
相关联的值,在本例中为null
。