How to properly make use of TestContext.Properties
You have to fix few things:
- TestInitialize method cannot be static and it shouldn't have any parameters
- You will need static method with ClassInitialize attribute and TestContext as parameter
- TestContext in your test class cannot be static
After that, you can access whatever properties you want in any unit tests. Here is an example:
[TestClass]public class GenerarBoletinDeClase{ public TestContext TestContext { get; set; } public static int Colegio { get; set; } [ClassInitialize] public static void ClassInitialize(TestContext testContext) { Colegio = int.Parse(testContext.Properties["colegio"].ToString()); // colegio is equal 7 in here } [TestInitialize] public void TestInitialize() { int tempColegio = int.Parse(this.TestContext.Properties["colegio"].ToString()); // colegio is equal 7 in here } [TestMethod] public void TestMethod1() { int colegio = int.Parse(this.TestContext.Properties["colegio"].ToString()); // colegio is equal 7 in here as well Assert.AreEqual(7, Colegio); Assert.AreEqual(7, colegio); Assert.AreEqual(colegio, Colegio); }}
First of all, thanks to @Peska for providing the code in this answer https://stackoverflow.com/a/51367231/5364231
So, finally what I did was add the following code to the class TestBase
:
public class TestBase{ public TestContext TestContext { get; set; } public static int Colegio { get; set; } [AssemblyInitialize] public static void ClassInitialize(TestContext TestContext) { Colegio = int.Parse(TestContext.Properties["colegio"].ToString()); // colegio is equal 7 in here } public TestBase() { SeleniumHelper = new HelperSelenium(Colegio, WebDriverSelector.ObtenerWebDriver()); DiccionarioCompartido = new Dictionary<string, string>(); }
The decorator [AssemblyInitialize]
is necessary, [ClassInitialize]
and [TestInitialize]
will not work, I believe because the TestContext has not been instantiated yet.
After that, make sure that you have configured a Test Settings File
by going to Test > Test Settings > Select Test Settings File
, the file must be named *.runsettings
With that, everything should be set up for TestContext.Properties
to read from your test settings file