Thank you for visiting! If you liked the site, please add a bookmark, else add a critical comment! Would you like to visit Greece? Traditional Greek flag This real estate site is only available in Greek! The holy mountain

Wednesday, 6 October 2010

JDeveloper 11g: Using assert() for testing and debugging

Assertions are a very useful feature for testing and debugging, but are rather neglected. Instead of using loggers to provide continuously diagnostic messages in critical programme  flow points, or even worse if- else - System.out.println() constructs, assert statements can only be enabled only when necessary. Thus, you avoid wasting valuable resources. In addition, you do not need to add any jar libraries to your IDE  project, or application server to use it. In order to use assert, you need to  pass the -ea argument, call a non void java method and check a Boolean  condition. For instance: assert(Month < 13). Nonetheless, you can not  use an assert statement to check the values passed to public methods. Consider for example the following code snippet, from an business components, employees entity object:
protected void doDML(int operation, TransactionEvent e) {
                if (operation == DML_UPDATE) {
               histStartDate = row.getEndDate();
              /*Check whether end date equals current date*/
              /*if (histStartDate.equals(new Date(Date.getCurrentDate()))){
                  System.out.println("End date equals current date!");
               assert(histStartDate.equals(new Date(Date.getCurrentDate() ) )) :
                          "End date equals current date! ";

Another trivial example from an ejb client follows:

public class PlaceBidClient {
    public static void main(String [] args) {
                     Bid bid = placeBid.addBid("Lila",  Long.valueOf(100),  2001.50);
                     System.out.println("Bid Successful, BidId Received is:" + bid.getBidId());
                     assert(bid.getBidId() == 502):"BidId Received is "+bid.getBidId();
Finally, when run, the log output reads:

-javaagent:C:\Oracle\Middleware\jdev_11gR1\jdeveloper\..\modules\org.eclipse.persistence_1.0.0.0_2-0.jar -Duser.language=en -ea actionbazaar.buslogic.client.PlaceBidClient

Exception in thread "main" java.lang.AssertionError: BidId Received is 393
    at actionbazaar.buslogic.client.PlaceBidClient.main(
Bid Successful, BidId Received is:393

No comments:

Post a Comment