JUNIT - testing for an exception


/ Published in: Java
Save to your folder(s)

example where you need to test for an exception


Copy this code and paste it in your HTML
  1. /** JUNIT TEST **/
  2.  
  3. inside XDAOTest.class
  4.  
  5. @Test
  6. public void testUpdateDcrWithForcedexception()
  7. {
  8. ICmsDcrDAO cmsDcrDAO = LSDAOFactory.getFactory().getCmsDcrDAO();
  9. String fakeSelect = "This is a fake Select to provoque SQLException ?";
  10. ReflectionTestUtils.setField(cmsDcrDAO, "UPDATE_DCR", fakeSelect);
  11. CmsDcr dcr = new CmsDcr();
  12. boolean testUpdate = cmsDcrDAO.updateDcr(dcr);
  13. assertFalse(testUpdate);
  14. }
  15.  
  16.  
  17. /** DAO CLASS **/
  18. inside XDAO.class
  19.  
  20. private static String UPDATE_DCR = "UPDATE seo_audit_data.cms_dcr SET dcr_path = ?, countPages = ?, date_last_updated = ?, isDeleted = ? WHERE id = ?";
  21.  
  22.  
  23. public boolean updateDcr(CmsDcr dcr) {
  24. conn = getDBConnection();
  25. boolean returnval = false;
  26. try {
  27. PreparedStatement preparedStatement = conn.prepareStatement(UPDATE_DCR);
  28. preparedStatement.setString(1, dcr.getDcrPath());
  29. preparedStatement.setInt(2, dcr.getCountPages());
  30. preparedStatement.setDate(3, dcr.getDateLastUpdated());
  31. preparedStatement.setInt(4, dcr.getIsDeleted());
  32. preparedStatement.setInt(5, dcr.getId());
  33. int rowsAffected = preparedStatement.executeUpdate();
  34. conn.close();
  35.  
  36. if(rowsAffected > 0) {
  37. returnval = true;
  38. }
  39. else{
  40. System.out.println("Unable to update dcr in seo_audit_data.cms_dcr table.");
  41. }
  42. }catch (SQLException e) {
  43. System.out.println("Database error trying to update the DCR in table seo_audit_data.cms_dcr." + e);
  44. }
  45. return returnval;
  46. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.