@Test public void createArticle() { String url = "www.koeckman.at"; int id = 1; final Article a = new Article(); a.setUrl(url); EntityManager mockEm = createMock(EntityManager.class); mockEm.persist(a); mockEm.flush(); EasyMock.expectLastCall() .andAnswer( new SideEffect() { @Override public void effect() throws Throwable { a.setId(1); } }); replay(mockEm); ArticleDao aDAO = new ArticleDao(); aDAO.setEntityManager(mockEm); Article result = aDAO.createArticle(a); Assert.assertEquals(a, result); verify(mockEm); }
@Test public void testupdateArticle() { String url = "test.at"; int id = 5; Article ar = new Article(); ar.setUrl(url); // QueryMock List<Object[]> returnList = new ArrayList<Object[]>(); Object[] retArr = new Object[2]; retArr[0] = id; retArr[1] = url; returnList.add(retArr); Query mockedQuery = createMock(Query.class); expect(mockedQuery.setParameter("url", url)).andReturn(mockedQuery); expect(mockedQuery.getResultList()).andReturn(returnList); replay(mockedQuery); EntityManager mockEm = createMock(EntityManager.class); expect(mockEm.createQuery("SELECT ar.id, ar.url FROM Article ar WHERE ar.url = :url")) .andReturn(mockedQuery); expect(mockEm.merge(ar)).andReturn(ar); mockEm.flush(); replay(mockEm); ArticleDao aDAO = new ArticleDao(); aDAO.setEntityManager(mockEm); // Test Article testResult = aDAO.updateArticle(ar); // Verify Assert.assertEquals(ar, testResult); verify(mockEm); }
@Test public void testdeleteArticle() { String url = "test.at"; int id = 5; Article ar = new Article(); ar.setUrl(url); ar.setId(id); EntityManager mockEm = createMock(EntityManager.class); expect(mockEm.find(Article.class, ar.getId())).andReturn(ar); mockEm.remove(ar); replay(mockEm); ArticleDao aDAO = new ArticleDao(); aDAO.setEntityManager(mockEm); // Test aDAO.deleteArticle(ar.getId()); // Verify verify(mockEm); }