when(mockEntityManager.createNamedQuery(eq(PackageVersion.QUERY_FIND_BY_PACKAGE_VER_ARCH))).thenReturn(
mockQuery);
List mockList = mock(List.class);
when(mockQuery.getResultList()).thenReturn(mockList);
when(mockList.size()).thenReturn(1);
final PackageVersion mockPackageVersion = mock(PackageVersion.class);
when(mockList.get(eq(0))).thenReturn(mockPackageVersion);
when(mockPackageVersion.getId()).thenReturn(0);
ContentManagerLocal mockContentManager = mock(ContentManagerLocal.class);
when(mockContentManager.persistPackageVersion(any(PackageVersion.class))).thenAnswer(
new Answer<PackageVersion>() {
public PackageVersion answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (PackageVersion) args[0];
}
});
when(mockEntityManager.find(eq(PackageVersion.class), eq(0))).thenAnswer(new Answer<PackageVersion>() {
public PackageVersion answer(InvocationOnMock invocation) throws Throwable {
return mockPackageVersion;
}
});
Package mockPackage = mock(Package.class);
when(mockPackageVersion.getGeneralPackage()).thenReturn(mockPackage);
Architecture mockArchitecture = mock(Architecture.class);
when(mockPackageVersion.getArchitecture()).thenReturn(mockArchitecture);
when(mockPackageVersion.getExtraProperties()).thenReturn(null);
//create object to test and inject required dependencies
ContentManagerBean objectUnderTest = new ContentManagerBean();
Field[] fields = ContentManagerBean.class.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals("entityManager")) {
field.setAccessible(true);
field.set(objectUnderTest, mockEntityManager);
field.setAccessible(false);
}
else if (field.getName().equals("contentManager")) {
field.setAccessible(true);
field.set(objectUnderTest, mockContentManager);
field.setAccessible(false);
}
}
//run the code to be tested
PackageVersion result = objectUnderTest.createPackageVersionWithDisplayVersion(mockSubject, packageName,
packageTypeID, version, displayVersion, architectureId, packageBitStream);
//verify the results (Assert and Mock Verification)
verify(mockList, times(1)).size();
verify(mockList, times(1)).get(eq(0));