【发布时间】:2016-09-28 20:34:01
【问题描述】:
我在静态类中有一个静态方法在单元测试中失败。问题是它需要来自不同静态类的公共静态属性的值。单元测试中属性的值始终为 null,因为源类未初始化。两个静态类都在同一个项目中。如果我直接执行该方法,我会得到想要的结果,但我无法使用测试。
静态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
}
}
静态 B 类:
public static class DbEng {
private static SQLiteConnection idbCn = new SQLiteConnection("Data Source=" + App.AppDir + "gcg.idb"); // App.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();
}
}
}
单元测试:
[TestClass]
public class DbEng_Tests {
[TestMethod]
public void PutIdbVal_Test() {
string TestKey = "Test-Key";
string TestValue = "Test - Value";
DbEng.PutIdbVal(TestKey, TestValue);
}
}
是否可以强制单元测试代码在调用静态类B中的方法之前初始化静态类A?
【问题讨论】:
-
你确定是因为静态类没有初始化吗? AppDomain 基目录更可能为 null,因为您正在单元测试中运行
-
您的代码依赖于静态变量的初始化顺序。由于这种顺序不是定义的行为,因此您观察到的行为非常好(不是您想要的,但也很好)。
-
由于您使用的是MSTest,您可以使用
[DeploymentItem]复制一个版本的gcg.idb 文件进行测试。见MSTest copy file to test run folder。虽然我更喜欢测试特定的配置文件... -
@CoolBots:我有“使用静态 [namespace].App;”在 B 类中,因此添加类前缀是多余的。我没有在示例中包含它 - 所以我的错。
-
@pro3carp3 啊,我没想到
using声明!我根据您的问题认为这不是问题,我只是认为在问题发布期间丢失了一些东西。很高兴这一切都解决了:)
标签: c# visual-studio unit-testing