-1

Hello I am have trouble using a method from an Instantiated class. I am rather new to selenium and C#, but here is my code to start...

class 1

 [TestClass]
    public class UnitTest1
    {
        Class2 myClass2 = new Class2();

        static IWebDriver webDriver;

        [AssemblyInitialize]
        public static void invokeBrowser(TestContext context)
        {
            webDriver = new ChromeDriver(@"C:\Selenium\");
        }

        [TestMethod]
        public void TestMethod1()
        {
            myClass2.RandomMethod();
        }

class 2

[TestClass]
    public class Class2
    {
        static IWebDriver webDriver;
        public void invokeBrowser(TestContext context)
        {
            webDriver = new ChromeDriver(@"C:\Selenium\");
        }


        [TestMethod]
        public void RandomMethod()
        {
            webDriver.Navigate().GoToUrl("http://google.com");
        }
    }

my error happens in Class1 during my testmethod that I am using to call the Randommethod from my other class

Message: Test method CheckRequest.UnitTest1.TestMethod1 threw exception: 
System.NullReferenceException: Object reference not set to an instance of an object.

I have been struggling with this error for a while and I just dont understand what I am doing wrong. The only object that I am setting is my webdriver. Is the issue that I am creating two different webdriver objects? Thanks for your time, and any help is much appreciated.

Bean0341
  • 1,632
  • 2
  • 17
  • 37
  • Your Class2 never actually instantiates the webDriver. Is that intentional? Just because you built it in Class1 doesn't mean anything to Class2. – Bob G Aug 09 '17 at 15:58
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – JeffC Aug 09 '17 at 16:34

1 Answers1

0
[TestClass]
    public class UnitTest1
    {
        Class2 myClass2 = new Class2();

        public static IWebDriver webDriver;

        [AssemblyInitialize]
        public static void invokeBrowser(TestContext context)
        {
            webDriver = new ChromeDriver(@"C:\Selenium\");
        }

        [TestMethod]
        public void TestMethod1()
        {
            myClass2.RandomMethod();
        }
}

//Class2
[TestClass]
    public class Class2
    {
        //[TestMethod]
        public void RandomMethod()
        {
            UnitTest1.webDriver.Navigate().GoToUrl("http://google.com");
        }
    }

[AssemblyInitialize] method will be called before any method in the project, so wedDriver will have value. TestMethod1 will call RandomMethod(), if you keep [TestMethod] for RandomMethod, it will be executed twice, as each [TestMethod] will be ran, when you run all the TestMethods. Is that what you need.

Vincent
  • 484
  • 4
  • 6
  • 21