繁体   English   中英

如何从单元测试中跳过构造函数调用?

[英]how to skip constructor call from unit test?

我正在为类方法“ Execute”之一执行单元测试,但不想执行类构造函数代码。

有什么方法可以跳过单元测试执行中的构造函数代码调用?

班级代码,

public class DemoCls
{
    public DemoCls()
    {
        string ConfigFolderPath = Path.Combine(Environment.CurrentDirectory, @"\Config");
        //string dataFolder = @"C:\Data1";
        foreach (string X in Directory.EnumerateFiles(ConfigFolderPath, "test" + "*.xml"))
        {
        }
    }

    public void Execute()
    {

    }
}

单元测试代码,

[TestClass()]
public class DemoClsTests
{
    [TestMethod()]
    public void ExecuteTest()
    {
        var X = new DemoCls();
        X.Execute();
    }
}

重写类,这是两种方法之一:

  1. 使用接口(可以在单元测试中模拟)将信息传递到构造函数中

     public interface IConfigFiles { List<string> Files { get; set; } } public DemoCls(IConfigFiles files) { } 
  2. 从构造函数中删除配置代码,然后将其放在其他函数中。

     public DemoCls() { // does nothing } public void Setup() { string ConfigFolderPath = Path.Combine(Environment.CurrentDirectory, @"\\Config"); //... } 

接口更适合单元测试。

“有没有办法从单元测试执行中跳过构造函数代码的调用?”

答案是:否(例如方法)

您可以将ctor代码包装在“ if”预处理程序指令中,并仅在非测试运行期间有条件地执行它。

#define DEBUG  
// ...  
#if DEBUG  
    Console.WriteLine("Debug version");  
#endif  

看到

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if

您可以使用一个单元测试框架,该框架允许您模拟具体的类,以便在没有接口的情况下伪造一个类,例如,我正在使用Typemock隔离器,并且我可以模拟几乎任何类,并确定所有类的情况成员及其构造函数。 这是您所遇到的课程的测试:

[TestMethod,Isolated]
public void TestMethod()
{
    var fake = Isolate.Fake.Instance<DemoCls>(Members.CallOriginal, ConstructorWillBe.Ignored);
    fake.Execute();

    Isolate.Verify.WasCalledWithAnyArguments(() => fake.Execute());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM