新Java運動:測試驅動開發3—使用者註冊4

來源:互聯網
上載者:User

完成資料庫操作的基礎架構之後,就是我們真正進行JDBC資料操作的時候了。所涉及的資料庫表ER圖如下所示:

如所示,我們第一步是向t_user表中添加記錄。由於使用者註冊需要操作多張表,因此需要用到事務,先寫出一個簡單的基於JDBC的事務架構,代碼如下所示:

@Overridepublic long registerUser(Map<String, Object> userInfo) {Connection conn = null;long userId = 0;try {conn = JdbcDs.getConnection();conn.setAutoCommit(false);userId = addUser(conn, userInfo);if (userId <= 0) {throw new SQLException("Fail to add user in t_user");}conn.commit();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();try {conn.rollback();} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}userId = -1;} finally {try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return userId;}

其次是具體的使用者添加操作,具體代碼如下所示:

private long addUser(Connection conn, Map<String, Object> userInfo) {long userId = -1;PreparedStatement stmt = null;ResultSet rst = null;String sql = "insert into t_user(user_name, user_group_id, user_level_id) values(?, 2, 1)";try {stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);stmt.setString(1, (String)userInfo.get("userName"));int affectedNum = stmt.executeUpdate();if (1 == affectedNum) {rst = stmt.getGeneratedKeys();if (rst.next()) {userId = rst.getLong(1);}} else {userId = -1;}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();userId = -1;} finally {try {if (rst != null) {rst.close();}if (stmt != null) {stmt.close();}} catch (Exception ex) {}}return userId;}

最後是改變測試案例中的判斷成功條件為所返回的userId大於0。

運行測試案例,應該可以成功通過測試案例。

經過以上幾篇文章,我們終於可以進行有意義的開發工作了。下一步就是實現所有使用者註冊商務邏輯,還有一塊是異常情況的處理,例如userName重複的情況。當完成所有這些功能後,我們還需要進行端到端測試,這就涉及通過JSP頁面進行註冊測試。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.