如何在运行单元测试时处理静态初始化?

时间:2014-05-25 17:54:14

标签: c# unit-testing

我有一些运行正常的代码,但我也会为它添加单元测试。我有问题不是测试本身,但使用静态初始化(构造函数和字段) - 它们不会被执行。

在第一次“触摸”时执行AFAIK静态初始化。我有类似的东西(依赖链):

public class A 
{
   public static readonly AFoo = "afoo";
}

public class B 
{
   public static readonly BFoo = new BFoo(A.AFoo);
}

public class C 
{
   public static readonly CFoo = new CFoo(B.BFoo);
}

在运行单元测试时,我会在随机位置看到空值,例如,所有突然的A.AFoo都不为空,但是B.BFoo是。

再一次,当“正常”运行代码时,一切都很好。

如何使静态初始化工作一如既往?

对于记录,我使用的静态字段是常量,通常为EmptyIdentifierEmptyPositionNoCoordinates所以我不必使用new Vector3d(0,0,0)之类的所有内容时间。

1 个答案:

答案 0 :(得分:0)

以下测试正常:

using FluentAssertions;

[TestClass]
public class SomeTests
{
    [TestMethod]
    public void TestTransitiveDependencies() 
    {
        C.CFoo.BFoo.str.Should().Be("afoo");
    }
}

我已经定义了类似于你的代码。

public class A { public static readonly string AFoo = "afoo"; }
public class B { public static readonly BFoo BFoo = new BFoo(A.AFoo); }
public class C { public static readonly CFoo CFoo = new CFoo(B.BFoo); }

但它没有编译,尽管我添加了这些类。

public class BFoo
{
    public readonly string str;
    public BFoo(string str) {this.str = str;}
}

public class CFoo
{
    public readonly BFoo BFoo;
    public CFoo(BFoo bFoo) {this.BFoo = bFoo;}
}

单个项目中的所有设置似乎都可以正常工作。 也许我们需要更多有关您的设置的信息。

工具链:VS2012 IDE,.NET 4.5运行时,Win7 OS

packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="FluentAssertions" version="2.2.0.0" targetFramework="net45" />
</packages>