创建更多可测试代码,同时避免 static/non-static 字段初始化程序问题

creating more testable code while avoiding static/non-static field initializer issues

我正在将一个非静态字符串传递到 MessageQueue:

public virtual MessageQueue MessageQueue { get; } = new MessageQueue(ConfigHelper.QLocation);

QLocation 是非静态的;但是,MessageQueue 需要一个静态参数。

我遇到了这个异常:

Cannot access a non-static field in static context

My ConfigHelper class 是我的配置文件值的包装器。我可以使 ConfigHelper class 静态;但是,这会使测试变得更加困难。

有没有办法解决这个问题,同时仍然保持代码的可测试性?

您正在尝试以静态方式使用 QLocation(ConfigHelper.QLocation),而它是一个非静态文件(如您所写...)

试试这个:

.... = new MessageQueue(new ConfigHelper().QLocation);

它将消除错误。

IMO,你应该通过这个 CUT(class under test) C'tor 注入 MessageQueue。您的 class 依赖于 MessageQueue。 如果您不想注入 MessageQueue 我建议您注入连接字符串而不是配置。