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

本文关键字:处理 静态 初始化 单元测试 何处理 运行 | 更新日期: 2023-09-27 18:05:09

我有一些运行良好的代码,但我也会为它添加单元测试。我遇到的问题不是测试本身,而是静态初始化(构造函数和字段)——它们没有被执行。

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是。

同样,当代码正常运行时,一切都很好。

我应该怎么做才能使静态初始化工作一如既往?

对于记录,我使用的静态字段是常量,通常是EmptyIdentifier, EmptyPosition, NoCoordinates,所以我不必一直使用像new Vector3d(0,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>