【问题标题】:How to write test case for static methods and static variables using wrapper class or dependency injection如何使用包装类或依赖注入为静态方法和静态变量编写测试用例
【发布时间】:2017-02-23 09:31:32
【问题描述】:

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

如果我为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
    }
}

【问题讨论】:

  • 你有什么版本的visual studio?为什么一定要xunit

标签: c# unit-testing xunit


【解决方案1】:

如果你只需要在构造函数中传递一个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);
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    相关资源
    最近更新 更多