user584018
user584018

Reputation: 11344

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.

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();
    }
}

Upvotes: 0

Views: 2438

Answers (4)

CorryM
CorryM

Reputation: 135

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. 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());
}

Upvotes: 0

m1kael
m1kael

Reputation: 2851

You could wrap you ctor code in the "if" preprocessor directive and execute it conditionally, only during a non-test run.

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

See

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

Upvotes: 0

user1023602
user1023602

Reputation:

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.

Upvotes: 5

Szer
Szer

Reputation: 3476

"Is there any way to skip constructor code call from the unit test execution?"

The answer is: No (for instance methods)

Upvotes: 3

Related Questions