This is a migrated thread and some comments may be shown as answers.

Global Functions

1 Answer 71 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
James
Top achievements
Rank 1
James asked on 18 Jun 2013, 06:36 PM
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:

http://www.telerik.com/automated-testing-tools/support/documentation/user-guide/code-samples/general/utility-in-standalone.aspx

My version of Test Studio is 2012.2.1527.0

Thank you for any help.

1 Answer, 1 is accepted

Sort by
0
Cody
Telerik team
answered on 18 Jun 2013, 08:19 PM
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
Regards,
Cody
Telerik
Free summer webinars on advanced web automation tactics hosted by Jim Holmes & Adam Goucher.
Reserve your seat today!
Tags
General Discussions
Asked by
James
Top achievements
Rank 1
Answers by
Cody
Telerik team
Share this question
or