问题
I need to test the following code.
public List<PatientGroup> findGroups(final String groupType) throws HwBaseAppException
{
assert groupType != null;//4 branches here
CriteriaBuilder criteriaBuilder=persistence.getCriteriaBuilder();
CriteriaQuery<PatientGroup> query = criteriaBuilder.createQuery(PatientGroup.class);
Root<PatientGroup> patientGroupRoot = query.from(PatientGroup.class);
Predicate condition=criteriaBuilder.equal(patientGroupRoot.get(PatientGroup_.active), Boolean.TRUE);
Join<PatientGroup, GroupSubType> groupSubTypeRoot = patientGroupRoot.join(PatientGroup_.groupSubType);
Predicate condition1=criteriaBuilder.equal(groupSubTypeRoot.get(GroupSubType_.groupTypeCode), groupType);
query.where(condition,condition1);
query.orderBy(criteriaBuilder.asc(patientGroupRoot.get(PatientGroup_.name)));
TypedQuery<PatientGroup> tq = persistence.createQuery(query);
List<PatientGroup> collections = tq.getResultList();
return initializeGroupRelationships(collections);
}
In my test case i am passing both null and not null values which should cover both the branches however Code coverage says 1 of 4 branches missed.What are the other 2 branches? Below are my test cases.
@Test
public void testFindGroups_1()
throws HwBaseAppException
{
Mockito.when(persistence.getCriteriaBuilder()).thenReturn(criteriaBuilder);
Mockito.when(criteriaBuilder.createQuery(PatientGroup.class)).thenReturn(criteriaQuery);
Mockito.when(criteriaQuery.from(PatientGroup.class)).thenReturn(patientGroupRoot);
Mockito.when(patientGroupRoot.join(PatientGroup_.groupSubType)).thenReturn(groupSubTypeRoot);
Mockito.when(persistence.createQuery(Mockito.any(CriteriaQuery.class))).thenReturn(tq);
Mockito.when(tq.getResultList()).thenReturn(arrayList);
Mockito.when(arrayList.iterator()).thenReturn(iterator);
Mockito.when(iterator.hasNext()).thenReturn(true).thenReturn(false);
Mockito.when(iterator.next()).thenReturn(patientGroup);
groupServiceDAOImpl.findGroups("groupType");
}
@Test(expected=AssertionError.class)
public void testFindGroups_2()
throws HwBaseAppException
{
groupServiceDAOImpl.findGroups(null);
}
回答1:
EclEmma Eclipse plugin provides coverage analysis using JaCoCo library, which in his turn analyzes bytecode. Let's take a simplified example:
class Example {
void example(Object x) {
assert x != null;
}
}
And let's have a look on its bytecode:
javac Example.java
javap -v Example
Which looks like:
0: getstatic #2 // Field $assertionsDisabled:Z
3: ifne 18
6: aload_1
7: ifnonnull 18
10: new #3 // class java/lang/AssertionError
13: dup
14: invokespecial #4 // Method java/lang/AssertionError."<init>":()V
17: athrow
18: return
As you can see - there are actually 2 conditions:
- assertions enabled (
ifne
) x
is notnull
(ifnonnull
)
And so 4 possible variants.
来源:https://stackoverflow.com/questions/41373770/how-does-assert-grouptype-null-contain-4-branches