本文介绍了System.TypeInitializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写测试以测试Infopath Forms以在Form Control中打开,我的测试方法为

I am writing tests to test Infopath Forms to open in Form Control, my test method is as

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

我将Helper类写为

I have written Helper class as

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

但是每次我执行这段代码,都会给我:

But everytime I execute this code, this gives me:

当我尝试调试时,它需要初始化Helper类时失败.这真是令人吃惊,有什么解决办法吗?

When I try to debug, it fails when Helper class needs to be initialized. This is really eating my head, is there any 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();
        }
    }
}

推荐答案

您的测试调用Helper.OpenForm(),并且由于您没有静态构造函数,因此,我看到的唯一会导致引发异常的事情是:

Your test calls Helper.OpenForm() and as you have no static constructor, the only thing I can see that would cause the exception to be thrown is:

private static MainForm f =  new MainForm();

因此,MainForm的构造函数中可能会引发异常.在MainForm的构造函数的 first 行上放置一个断点,并逐步执行,直到看到引发异常的位置为止.

Therefore something in the constructor for MainForm is likely throwing an exception. Put a breakpoint on the first line of the constructor for MainForm and step through until you see where the exception is thrown.

或者,您可能会发现,至少在最初阶段,更容易确定问题所在,通过编写新的测试,您可以逐步完成直接调用new MainForm()的测试:

Alternatively you might find it easier to determine what the problem is, at least initially, by writing a new test you can step through that calls new MainForm() directly:

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

在测试的唯一行上放置一个断点,然后进入构造函数,以确定为什么要抛出NullReferenceException.

Put a breakpoint on the only line of the test and step into the constructor to determine why it's throwing a NullReferenceException.

这篇关于System.TypeInitializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-17 05:42