Read

Here are the tests for Sql2oCourseDao.read method:

@Test
@DisplayName("read a course given its offering name")
void readCourseGivenOfferingName() {
  for (Course c2 : samples) {
    Course c1 = courseDao.read(c2.getOfferingName());
    assertEquals(c2, c1);
  }
}
@Test
@DisplayName("read returns null given invalid offering name")
void readCourseGivenInvalidOfferingName() {
  Course c1 = courseDao.read("EN.00.999");
  assertNull(c1);
}

Here is the implementation of Sql2oCourseDao.read method:

@Override
public Course read(String offeringName) throws DaoException {
  try (Connection conn = sql2o.open()) {
    return conn.createQuery("SELECT * FROM courses WHERE offeringName = :name;")
        .addParameter("name", offeringName)
        .executeAndFetchFirst(Course.class);
  } catch (Sql2oException ex) {
    throw new DaoException("Unable to read a course with offeringName " + offeringName, ex);
  }
}

Run the tests and make sure they pass!

readAll

Here is a test for Sql2oCourseDao.readAll method:

@Test
@DisplayName("read all the courses")
void readAll() {
  List<Course> courses = courseDao.readAll();
  assertIterableEquals(samples, courses);
}

Here is the implementation of Sql2oCourseDao.readAll:

@Override
public List<Course> readAll() throws DaoException {
  try (Connection conn = sql2o.open()) {
    return conn.createQuery("SELECT * FROM courses;").executeAndFetch(Course.class);
  } catch (Sql2oException ex) {
    throw new DaoException("Unable to read courses from the database", ex);
  }
}

Run the test and make sure it passes!

Overloaded readAll

Here are the tests for the overloaded Sql2oCourseDao.readAll method:

@Test
@DisplayName("read all the courses that contain a query string in their title")
void readAllGivenTitle() {
  String query = "data";
  List<Course> courses = courseDao.readAll(query);
  assertNotEquals(0, courses.size());
  for (Course course : courses) {
    assertTrue(course.getTitle().toLowerCase().contains(query.toLowerCase()));
  }
}

Notice the assertion statement implies the "search" must be case insensitive.

@Test
@DisplayName("readAll(query) returns empty list when query not matches courses' title")
void readAllGivenNonExistingTitle() {
  String query = "game";
  List<Course> courses = courseDao.readAll(query);
  assertEquals(0, courses.size());
}

As part of HW5 it is left to you to implement the overloaded Sql2oCourseDao.readAll method!

@Override
public List<Course> readAll(String titleQuery) throws DaoException {
  return null; // TODO Implement me
}