I have the following static class:
public static class UnitTestDefinitions
{
public static int Foo = 4;
/// <summary>
/// static constructor
/// </summary>
static UnitTestDefinitions()
{
InitAccounts();
}
private static void InitAccounts()
{
// some code
}
// more code
}
I have a NUnit test that fails to run because I cannot access Foo
:
The actual exception that I get is:
System.TypeInitializationException was unhandled by user code
HResult=-2146233036 Message=The type initializer for 'Ublux.Communications.PrimaryService.UnitTestDefinitions' threw an exception. Source=Ublux.Communications.CoreService
TypeName=Ublux.Communications.PrimaryService.UnitTestDefinitions
StackTrace: at Ublux.Communications.CoreService.UnitTests.TestCloudServicesCore.TestAuthentication() in C:\GIT\Ublux\Ublux Communications Core Service\Ublux.Communications.CoreService\Ublux.Communications.CoreService\UnitTests\TestCloudServices_Core.cs:line 146 InnerException: HResult=-2146233040 Message=Exception of type 'System.Threading.ThreadAbortException' was thrown.
I been using c# for a while so to me it is obvious that the problem has to be in the static constructor, In other words there has to be a problem with the method InitAccounts()
.
Because of that I REMOVED the static constructor on the static class UnitTestDefinitions and call the InitAccounts()
method manually as:
The user has no control on when the static constructor is executed in the program. If your InitAccounts()
method is attempting to access objects that haven't been initialized yet, you may get an exception. Since you haven't provided that code, it's hard to say. This is one big reason for avoiding static classes altogether (use a Singleton if necessary).