This is a migrated thread and some comments may be shown as answers.

Mocking Static Private Constructor

1 Answer 45 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Danny
Top achievements
Rank 1
Danny asked on 18 Oct 2011, 07:45 PM
Hi,

Is there a way to mock a private static constructor?

I got an static class with a private static constructor and I don't want to execute it because it configures himself from a configuration within the app.config.

I just want to mock one of is method but the constructor is always call causing the test to throw an exception.

Here an example thats illustrate my problem:

I got a static class like this

public static class StaticClassWithPrivateStaticConstructor
{
    private static string _text = "Text";
    static StaticClassWithPrivateStaticConstructor()
    {
        throw new Exception();
    }
    public static string Text
    {
        get { return _text; }
    }
}

I want to be able to test Text property without executing the static constructor.

[TestMethod]
public void MockStaticConstructor()
{
    Mock.SetupStatic(typeof(StaticClassWithPrivateStaticConstructor));
    Assert.AreEqual("Text", StaticClassWithPrivateStaticConstructor.Text);
}

Is there a way to do this?

Thanks

1 Answer, 1 is accepted

Sort by
0
Ricky
Telerik team
answered on 20 Oct 2011, 10:56 AM
Hi Danny,

Thanks again for contacting us.

I checked the issue and it is possible to fake out the static constructor while you do Mock.SetupStatic. In that case, i would ask you to create a ticket so that i can send you an internal build with the feature included (you need to create the ticket (addressed to me) since i can't send internal builds to public forum).

 

Kind Regards,
Mehfuz
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

Tags
General Discussions
Asked by
Danny
Top achievements
Rank 1
Answers by
Ricky
Telerik team
Share this question
or