]> git.somenet.org - pub/jan/dst18.git/blob - ass1-jpa/src/test/java/dst/ass1/jpa/examples/ExampleTestWithCustomTestData.java
Add template for assignment 1
[pub/jan/dst18.git] / ass1-jpa / src / test / java / dst / ass1 / jpa / examples / ExampleTestWithCustomTestData.java
1 package dst.ass1.jpa.examples;
2
3 import static org.hamcrest.CoreMatchers.is;
4 import static org.junit.Assert.assertThat;
5
6 import java.util.List;
7
8 import javax.persistence.EntityManager;
9
10 import org.junit.Rule;
11 import org.junit.Test;
12
13 import dst.ass1.jpa.ITestData;
14 import dst.ass1.jpa.ORMService;
15 import dst.ass1.jpa.dao.ICoursePlatformDAO;
16 import dst.ass1.jpa.model.ICoursePlatform;
17 import dst.ass1.jpa.model.IModelFactory;
18
19 /**
20  * This examples shows how you can write your own tests with custom fixtures that are injected it into the
21  * {@link ORMService} rule. Using rules instead of abstract tests is considered good practice as it follows the
22  * principle of composition over inheritance.
23  */
24 public class ExampleTestWithCustomTestData {
25
26     @Rule
27     public ORMService orm = new ORMService(new MyTestData());
28
29     @Test
30     public void coursePlatformDAO_findAll_returnsCorrectValues() throws Exception {
31         ICoursePlatformDAO coursePlatformDAO = orm.getDaoFactory().createCoursePlatformDAO();
32
33         List<ICoursePlatform> all = coursePlatformDAO.findAll();
34
35         assertThat(all.isEmpty(), is(false));
36         assertThat(all.size(), is(2));
37
38         System.out.println(all);
39     }
40
41     @Test
42     public void coursePlatformDAO_findById_returnsCorrectValue() throws Exception {
43         ICoursePlatformDAO coursePlatformDAO = orm.getDaoFactory().createCoursePlatformDAO();
44
45         ICoursePlatform actual = coursePlatformDAO.findById(1L);
46
47         assertThat(actual.getUrl(), is("http://cp1.example"));
48     }
49
50     public static class MyTestData implements ITestData {
51
52         @Override
53         public void insert(IModelFactory modelFactory, EntityManager em) {
54             ICoursePlatform cp1 = modelFactory.createCoursePlatform();
55             cp1.setName("cp1");
56             cp1.setUrl("http://cp1.example");
57
58             ICoursePlatform cp2 = modelFactory.createCoursePlatform();
59             cp2.setName("cp2");
60             cp2.setUrl("http://cp1.example");
61
62             em.persist(cp1);
63             em.persist(cp2);
64
65             em.flush(); // transaction is done through the ORMTestFixture
66         }
67     }
68 }