eObject;
List writers = book.getWriter();
if (writers.size() == 3)
return true;
}
return false;
}
}
自己编写的Condition类并没有什么特殊之处,其使用方法与库中的条件类是完全一样的:
代码 4 使用新建的Condition类
public Collection queryBookWithThreeWriters(EObject root) {
SELECT select = new SELECT(new FROM(root), new WHERE(
new ThreeWriterCondition()));
return select.execute();
}
使用EMF Query查询EMF模型(4)
时间:2011-02-12 IBM 郝萍
4 测试结果
最后,我们可以使用JUnit来测试我们的查询代码。由于我们的项目基于JDK 5.0开发,因而我们可以使用JUnit 4.0来进行测试。JUnit 4.0充分利用了JDK 5.0中引入的Annotation机制,在代码编写方面与之前的版本有着相当大的区别。当然,它还是一样的简单易用。下面就是我们用于测试三个 Query函数的测试方法。
代码 5 使用JUnit 4.0测试查询
@Test
public void testQueryLargeBook() {
Collection books = query.queryLargeBook(library);
if (books.size() < 1)
fail("No large book is found");
for (Iterator iter = books.iterator(); iter.hasNext();) {
Book element = (Book) iter.next();
if (element.getPages() < 500)
fail("Small book is found in the result");
}
}
@Test
public void testQueryBookByWriter() {
Collection books = query.queryBookByWriter(library, writer);
if (books.size() < 1)
fail("No book is found");
for (Iterator iter = books.iterator(); iter.hasNext();) {
Book book = (Book) iter.next();
if (!book.getWriter().contains(writer))
fail("Found a book which is not authored by "
+ writer.getName());
}
}
@Test
public void testQueryBookWithThreeWriters() {
Collection books = query.queryBookWithThreeWriters(library);
if (books.size() < 1)
fail("No book is found");
for (Iterator iter = books.iterator(); iter.hasNext();) {
Book book = (Book) iter.next();
if (book.getWriter().size() != 3)
fail("Found a book which has less than three authors");
}
}
在编写测试用例时,JUnit 4.0不再强制要求我们遵守方法的命名规则。相反,只要用@Test标注过的方法,就是测试方法。另外,在测试执行之前,我们首先需要生成一个测试用的模型,这可以通过下面的代码来完成:
代码 6 生成测试用Library模型
@Before
public void setUp() throws Exception {
lp = LibraryPackage.eINSTANCE;
lf = LibraryFactory.eINSTANCE;
library = lf.createLibrary();
writer = lf.createWriter();
writer.setName("James Gan");
Writer writer1 = lf.createWriter();
writer1.setName("Ping Hao");
library.getWriters().add(writer1);
Writer writer2 = lf.createWriter();
writer2.setName("Qiu Qiu");
library.getWriters().add(writer2);
Book book = lf.createBook();
book.setTitle("How to Query with EMF Query");
book.setPages(1000);
book.getWriter().add(writer);
library.getBooks().add(book);
Book
|