Date calculator : Selenium Web Driver

How can I verify if the calculated date is correct through selenium web driver? Consider the following examples below:

From Date: 01/01/2001 Duration: 10 To Date: 01/10/2001

I will instruct selenium to input a date on from date field and duration. The system shall automatically calculates the To date based on the inputted from date and duration.

I wonder if there's a way to verify if the calculated To Date is correct given that the inputted values on from date and duration fields may change time to time.

Static values for from date and duration fields is okay too - I guess.

Thanks!

Upvotes: 0

Views: 2744

Answers (2)

Erki M.
Erki M.

Reputation: 5072

I suggest parsing the date instead of splitting the string

String strDate = "01/01/2001";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = simpleDateFormat.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 10); // 10 == duration
String outStr = simpleDateFormat.format(calendar.getTime());

Upvotes: 1

Husam
Husam

Reputation: 1105

You can do this using java.util methods. I assume you will be pass From Date and Duration as string to your selenium/webdriver from your test data set. You have to do following for each test data:

  • Calculate the To Date using util method (Code below for getToDate).
  • Get text in To Date using selenium/webdriver, for your test data.
  • Compare the text fetched by selenium/webdriver with the text returned by your getToDate method.

The method to get To Date:

public static String getToDate(String fromDate, String duration){
    try {
        String[] arrFromDate = fromDate.split("/");
        int fromMonth = Integer.parseInt(arrFromDate[0])-1;
        int fromDay = Integer.parseInt(arrFromDate[1]);
        int fromYear = Integer.parseInt(arrFromDate[2]);
        int intDuration = Integer.parseInt(duration);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, fromDay);
        cal.set(Calendar.MONTH, fromMonth);
        cal.set(Calendar.YEAR, fromYear);   
        cal.add(Calendar.DAY_OF_MONTH, intDuration);
        String toDate = sdf.format(cal.getTime());
        return toDate;
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return null;
    }

Code to verify:

String appToDate = driver.findElement(By.id("toDate")).getText();
String myToDate = getToDate("01/01/2001","10");
boolean isToDateCorrect = false;
if (appToDate.equals(myToDate )){
    isToDateCorrect  = true;
}

Upvotes: 1

Related Questions