简体   繁体   English

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

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

I am executing unit test for one of class method "Execute", but don't want to execute class constructor code. 我正在为类方法“ Execute”之一执行单元测试,但不想执行类构造函数代码。

Is there any way to skip constructor code call from the unit test execution? 有什么方法可以跳过单元测试执行中的构造函数代码调用?

Class Code, 班级代码,

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()
    {

    }
}

Unit Test Code, 单元测试代码,

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

Rewrite the class, one of two ways: 重写类,这是两种方法之一:

  1. Pass the information into the constructor using an interface (which can be mocked in unit-tests) 使用接口(可以在单元测试中模拟)将信息传递到构造函数中

     public interface IConfigFiles { List<string> Files { get; set; } } public DemoCls(IConfigFiles files) { } 
  2. Remove configuration code from the constructor, and put it in a different function instead. 从构造函数中删除配置代码,然后将其放在其他函数中。

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

Interfaces are better for unit-testing. 接口更适合单元测试。

"Is there any way to skip constructor code call from the unit test execution?" “有没有办法从单元测试执行中跳过构造函数代码的调用?”

The answer is: No (for instance methods) 答案是:否(例如方法)

You could wrap you ctor code in the "if" preprocessor directive and execute it conditionally, only during a non-test run. 您可以将ctor代码包装在“ if”预处理程序指令中,并仅在非测试运行期间有条件地执行它。

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

See 看到

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

You can use a unit testing frameworks that allows you to mock concrete classes in order to fake a class without an interface, for example i'm using Typemock Isolator and with that i can mock almost any class and decide what is happening with all the class's members and its constructor. 您可以使用一个单元测试框架,该框架允许您模拟具体的类,以便在没有接口的情况下伪造一个类,例如,我正在使用Typemock隔离器,并且我可以模拟几乎任何类,并确定所有类的情况成员及其构造函数。 here is a test for the class that you had in your question: 这是您所遇到的课程的测试:

[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