Create
Here are the tests for Sql2oCourseDao.create
method:
@Test
@DisplayName("create works for valid input")
void createNewCourse() {
Course c1 = new Course("EN.601.421", "Object-Oriented Software Engineering");
Course c2 = courseDao.create(c1.getOfferingName(), c1.getTitle());
assertEquals(c1, c2);
}
@Test
@DisplayName("create throws exception for duplicate course")
void createThrowsExceptionDuplicateData() {
assertThrows(DaoException.class, () -> {
courseDao.create("EN.500.112", "GATEWAY COMPUTING: JAVA");
});
}
@Test
@DisplayName("create throws exception for invalid input")
void createThrowsExceptionIncompleteData() {
assertThrows(DaoException.class, () -> {
courseDao.create(null, null);
});
}
And here is the implementation of Sql2oCourseDao.create
:
@Override
public Course create(String offeringName, String title) throws DaoException {
String sql = "WITH inserted AS ("
+ "INSERT INTO courses(offeringName, title) VALUES(:name, :title) RETURNING *"
+ ") SELECT * FROM inserted;";
try (Connection conn = sql2o.open()) {
return conn.createQuery(sql)
.addParameter("name", offeringName)
.addParameter("title", title)
.executeAndFetchFirst(Course.class);
} catch (Sql2oException ex) {
throw new DaoException(ex.getMessage(), ex);
}
}
Run the tests and make sure they pass!