vbscripthp-uft

UFT - Random Date


I create this code do get a random Date in a Range. I support it from some sites and answers here at stack from others. This works whit no problems, but when i try too pass at one function keep giving error.

StartDate = "01-01-1950"
EndDate= "31-12-2000"

StartDate = CDate(StartDate)
EndDate= CDate(EndDate)

Randomize
dtmRandomDate = DateValue((EndDate- StartDate + 1) * Rnd + StartDate )


Browser("DashBoard_2").Page("DashBoard").WebEdit("txtBornDate").Set dtmRandomDate

The error:

enter image description here

The function:

Function DataRandom(StartDate, EndDate)

    Dim StartDate, EndDate

    StartDate = CDate(StartDate)
    EndDate= CDate(EndDate)

    Randomize
    dtmRandomDate = EndDate((dtmEndDate - StartDate+ 1) * Rnd + StartDate)

End Function

I think the problem it's in the way i pass the Variables. Something about date functions that im missing it to declare, making the variable accept the date? It's something about the UFT system himself?

Already try somethings, but didnt worked.

Thank You, Best Regards


Solution

  • Can see from the test that it's failing on line 130;

    a = DataRandom(01-02-2020, 03-04-2022)
    

    There are two issues here:

    1. The function DateRandom() expects to return a value but the function definition does not contain a statement to return the result and is behaving more like a Sub Procedure than a Function. To fix this change the Function definition to;

      Function DataRandom(StartDate, EndDate)
          Dim StartDate, EndDate
      
          StartDate = CDate(StartDate)
          EndDate = CDate(EndDate)
      
          Randomize 'Should be initialised once rather than with each call to the function.
          dtmRandomDate = DateValue((EndDate - StartDate + 1) * Rnd + EndDate)
      
          DateRandom = dtmRandomDate 'This line returns the result.
      End Function
      
    2. The arguments being passed to the function are syntactically problematic, as you use CDate() to convert the values to correct Date you should pass the values as strings. Which just requires encapsulating each argument in double-quotes in the test.

      a = DataRandom("01-02-2020", "03-04-2022")
      

    Also as pointed out in the comments the Randomize statement should only be run once rather than with each call to the function. Ideally you would have an Init() procedure that deals with the script setup and initialisation.