Global Functions

2 posts, 0 answers
  1. James
    James avatar
    6 posts
    Member since:
    May 2013

    Posted 18 Jun 2013 Link to this post

    Hi Telerik Team,

    I have a method that generates a random number that is used to populate a textbox. This code works fine within a test but I would like to move it into a separate library where all my tests within the project can access & use it (the broader goal being to put multiple methods in one place).

    So right now I have WebTest1 which has a coded step to call this function (getNumber) however it is failing with this error:

    c:\QA_Test_Automation\Test Suite\Work In Progress\WebTest1.tstest.cs: Line 82: (CS0120) An object reference is required for the non-static field, method, or property 'Test_Suite.Utility.getNumber()'

    Here is how I am calling the method from within WebTest1.tstest:

    [CodedStep(@"Enter text '' in 'TxtSearchText'")]
            public void WebTest1_CodedStep()
                int randomNum = Utility.getNumber();
                Actions.SetText(Pages.COBRApointTPAPortalHome.TxtSearchText, randomNum.ToString());

    And here is how I have the method setup within the UtilityTest1.tstest:

    public class Utility {
            public void getNumber(){
             System.Random random = new System.Random();
                int randomNum = random.Next(100000000,999999999);

    Both files exist within the same project. Any clue on what I am doing wrong? I was also following this link:

    My version of Test Studio is 2012.2.1527.0

    Thank you for any help.
  2. Cody
    Cody avatar
    3354 posts

    Posted 18 Jun 2013 Link to this post

    Hello James,

    This is a basic programming problem. Since getNumber is not declared as a static method, the compiler is expecting you to create a new instance of your Utility class and calling the getNumber method of the new instance.

    Since this isn't required for this method you can declare the method to be static like this:

    public static int getNumber()
        System.Random random = new System.Random();
        return random.Next(100000000, 999999999);

    Now you don't need an object reference to use the method. Note I had to make a couple other changes in order for your method to work the way you want:

    1. It needs to return an int instead of a void
    2. The second line of code returns the value instead of only storing it in a variable
    Free summer webinars on advanced web automation tactics hosted by Jim Holmes & Adam Goucher.
    Reserve your seat today!
Back to Top