i wish test persistence in my application, so i wrote this test using arquillian.
@RunWith(Arquillian.class)
public class FeaturesPersistenceTest {
@Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(Feature.class.getPackage())
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static final String[] FEATURE_NAME = {
"Feature1",
"Feature2",
"Feature3"
};
@PersistenceContext(name = "testPU")
EntityManager em;
@Inject
UserTransaction utx;
@Before
public void preparePersistenceTest() throws Exception {
clearData();
insertData();
startTransaction();
}
@After
public void commitTransaction() throws Exception {
utx.commit();
}
private void clearData() throws Exception {
utx.begin();
em.joinTransaction();
System.out.println("Dumping old records...");
em.createQuery("delete from Feature").executeUpdate();
utx.commit();
}
private void insertData() throws Exception {
utx.begin();
em.joinTransaction();
System.out.println("Inserting records...");
for (String name : FEATURE_NAME) {
Feature feature = new Feature(name, name);
em.persist(feature);
}
utx.commit();
// clear the persistence context (first-level cache)
em.clear();
}
private void startTransaction() throws Exception {
utx.begin();
em.joinTransaction();
}
@Test
public void shouldFindAllFeaturesUsingJpqlQuery() throws Exception {
System.out.println("Selecting (using JPQL)...");
List<Feature> features = em.createNamedQuery("Feature.findAll", Feature.class).getResultList();
System.out.println("Found " + features.size() + " features (using JPQL):");
assertContainsAllFeatures(features);
}
/**
* Using a separate method for assertions provides two benefits:
* It clearly explains what we are expecting
* It can be reused in other tests
*
*/
private static void assertContainsAllFeatures(Collection<Feature> retrievedFeatures) {
Assert.assertEquals(FEATURE_NAME.length, retrievedFeatures.size());
final Set<String> retrievedFeatureTitles = new HashSet<>();
for (Feature feature : retrievedFeatures) {
System.out.println("* " + feature);
retrievedFeatureTitles.add(feature.getName());
}
Assert.assertTrue(retrievedFeatureTitles.containsAll(Arrays.asList(FEATURE_NAME)));
}
}
it returns greenbar, but why it write nothing in the test output nor in server output?
is it normal that it takes long time? (about 300s)
Aucun commentaire:
Enregistrer un commentaire