1

I have two Selenium C# test case classes, ClassA and ClassB. I would like to reuse a static variable VarA, defined in another static non-test ClassC. After ClassA has made a change to the variable, I would like that when test methods in ClassB launch to use the new VarA value.

My question is, having two [TestClass] in C# (ClassA and ClassB), how can one use a static variable from a non-test static class to share data between the two tests classes?

Paul Muir
3,28219 silver badges35 bronze badges
asked Nov 8, 2018 at 14:12

3 Answers 3

1

I suppose it depends on how they are being ran but generally speaking so long as you are not tearing down your AppDomain I believe it should keep your variable across the tests if it is in a static class.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PaulTest
{
 [TestClass]
 public class ClassA
 {
 [TestMethod]
 public void ClassATest()
 {
 ClassC.VarA = "Test";
 Assert.AreEqual("Test", ClassC.VarA);
 }
 }
 [TestClass]
 public class ClassB
 {
 [TestMethod]
 public void ClassBTest()
 {
 Assert.AreEqual("Test", ClassC.VarA);
 }
 }
 public static class ClassC
 {
 public static string VarA { get; set; }
 }
}

In this the tests are passing using the built in VS Test framework when running them all together.

answered Nov 14, 2018 at 21:14
0

The could both inherit from the same class which could set and get data using public class methods. To keep this safe make that data structure independent from other non class methods and copy into it by value.

answered Nov 8, 2018 at 16:00
0

First of all, it sounds like bad design because you're making test B dependent on test A. If A fails, then B will fail also. If possible, get and/or set up data for test B in ClassB itself.

Secondly, if running test A returns data that is used as input for test B, considering the following:

  • Wouldn't it be better to combine these tests as (an end-to-end) flow, if they are dependent anyway?
  • Or, make both tests inherit from the same base class, at least allowing you to remove the static.
  • Or, as suggested above, can't we fetch that data (via SQL or API) in test B itself?
  • Also, you'd need to prioritize your tests so you're sure test A is always run before test B (which inherently isn't guaranteed).
answered Aug 12, 2019 at 6:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.