System.TypeInitializationException

I am writing tests to test Infopath forms for opening in Form Control, my testing method is

[TestMethod]
public void Validate_OpenInfopathInFormControl()
{
    Helper.OpenForm();
    //Other Code    
}

I wrote the Helper class as

public class Helper
{  
    public static void OpenForm()
    {
        //Code to Open Form
    }
}

But every time I execute this code, it gives me:

The test method InfoPathTest.TestAPI.Validate_OpenInfopathInFormControl threw an exception: System.TypeInitializationException: The type initializer for "InfoPathTest.Helpers.Helper" threw an exception. ---> System.NullReferenceException: the reference object is not set to an instance of the object ..

When I try to debug, it fails when the Helper class needs to be initialized. It really is my head, is there a solution for this?

Here is the complete helper class:

namespace InfoPathTest.Helpers
{
    public class Helper
    {
    //This is the form i need to OPEN
        private static MainForm f =  new MainForm();
        private static bool _isOpen = false;

        public static bool isOpen
        {
            set { _isOpen = value; }
            get { return _isOpen; }
        }

        public static void OpenForm()
        {
            try
            {
                f.Show();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            _isOpen = true;

        }

        public static void CloseForm()
        {
            f.Hide();
        }
    }
}
+5
source share
3

Helper.OpenForm(), , , , , :

private static MainForm f =  new MainForm();

- MainForm, , . MainForm , , .

, , , , , new MainForm():

[TestMethod]
public void Validate_OpenInfopathInFormControl()
{
    var form = new MainForm();
}

, , NullReferenceException.

+6

- , ; , :

private static MainForm f =  new MainForm();
private static bool _isOpen = false;

bool - , , MainForm.

TypeInitializationException ? , .

+3

( Type Initializers). - NullReference. , .

The rules determine when type initializers start, are complex, but it is guaranteed that they are executed before you access the type in any way. It may not be directly obvious to you that you have a type initializer in the class Helper, because you can use implicit initialization:

public class Helper
{   
    static int i = 10; // This assignment will end up in a type initializer
    static Helper()
    {
        // Explicit type initializer
        // The compiler will make sure both, implicit and explicit initializations are run
    }
}
+1
source

All Articles