Update
Here are the tests for Sql2oCourseDao.update
method:
@Test
@DisplayName("updating a course works")
void updateWorks() {
String title = "Updated Title!";
Course course = courseDao.update(samples.get(0).getOfferingName(), title);
assertEquals(title, course.getTitle());
assertEquals(samples.get(0).getOfferingName(), course.getOfferingName());
}
@Test
@DisplayName("Update returns null for an invalid offeringCode")
void updateReturnsNullInvalidCode() {
Course course = courseDao.update("EN.000.999", "UpdatedTitle");
assertNull(course);
}
@Test
@DisplayName("Update throws exception for an invalid title")
void updateThrowsExceptionInvalidTitle() {
assertThrows(DaoException.class, () -> {
courseDao.update(samples.get(0).getOfferingName(), null);
});
}
And here is the implementation of Sql2oCourseDao.update
:
@Override
public Course update(String offeringName, String title) throws DaoException {
String sql = "WITH updated AS ("
+ "UPDATE courses SET title = :title WHERE offeringName = :name RETURNING *"
+ ") SELECT * FROM updated;";
try (Connection conn = sql2o.open()) {
return conn.createQuery(sql)
.addParameter("title", title)
.addParameter("name", offeringName)
.executeAndFetchFirst(Course.class);
} catch (Sql2oException ex) {
throw new DaoException("Unable to update the course", ex);
}
}
Run the tests and make sure they pass!