首页 文章

如何使用包装类或依赖注入编写静态方法和静态变量的测试用例

提问于
浏览
0

我的要求是需要使用xunit为 Example1 视图模型编写测试用例 . 此视图模型初始化 Example2 视图模型 . 但是 Example2 在构造函数中包含静态方法,而静态方法包含一个静态变量 .

如果我为 Example1 编写了一个测试用例,测试用例在运行所有测试用例时失败,但在运行选定的测试用例时会通过 . 因为在 Example2 中使用静态方法 .

我已尝试将静态方法和变量更改为非静态但其抛出 System.TypeInitializationException 异常 .

任何人都可以为此解释或举例吗?没有删除静态关键字我怎么能实现这一点?任何人都可以给一个指导?

例:

public class Example1
{
    public Example1(Example2 example2) { ... }
}   

public class Example2
{
    public Example2()
    {
        SomeStaticMethod() //static method inside the constructor
    }

    static SomeStaticMethod()
    {
        logPath = ""; //logPath is the static variable which is declared in another static class
    }
}

1 回答

  • 0

    如果您只需要在构造函数中传递 Example2 的实例,那么它非常简单:

    namespace Tests
    {
      using Xunit;
    
      using XunitSample;
    
      public class Class1
      {
        [Fact]
        public void Example1_Test()
        {
          var ex2 = (Example2)System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(Example2));
    
          var target = new Example1(ex2);
    
          Assert.NotNull(target);
        }
      }
    }
    

相关问题