lundi 30 mai 2016

Unit Test Fails due to uninitialized static property

I have a static method in a static class that fails under unit testing. The problem is that it requires the value of a public static property from a different static class. The value of the property in the unit test is always null because the source class is not initialized. Both static classes are in the same project. If I execute the method directly, I get the desired results, but I am unable to use a test.

Static Class A:

static class App {

  private static string appDir;

  public static string AppDir => appDir;

  [STAThread]
  static void Main() {

    appDir = AppDomain.CurrentDomain.BaseDirectory;

    DbEng.PutIdbVal("x", "Y");  // Method under test - Works here

  }
}

Static Class B:

public static class DbEng {

  private static SQLiteConnection idbCn = new SQLiteConnection("Data Source=" + AppDir + "gcg.idb"); // AppDir is valid when not testing, is null when testing.

  public static void PutIdbVal(string key, string value) {

  using (var cmd = new SQLiteCommand("INSERT INTO tKv (Key, Value) VALUES (@key, @value)", idbCn)) {
      cmd.Parameters.Add(new SQLiteParameter("@key", key));
      cmd.Parameters.Add(new SQLiteParameter("@value", value));
      idbCn.Open();
      cmd.ExecuteNonQuery();
      idbCn.Close();
    }
  }
}

Unit Test:

[TestClass]
public class DbEng_Tests {
  [TestMethod]
  public void PutIdbVal_Test() {

    string TestKey = "Test-Key";
    string TestValue = "Test - Value";

    DbEng.PutIdbVal(TestKey, TestValue);

  }
}

Is it possible to force the unit testing code to initialize static class A before calling the method in static class B?

Aucun commentaire:

Enregistrer un commentaire