.netvb.netnullreferenceexceptiontypeinitializationexception

TypeInitializationException and NullReferenceException in Gallio when calling a shared member of a class


I'm trying to use Gallio and MbUnit (version 3.2.750).

As per the tutorial ( http://gallio.org/wiki/doku.php?id=getting_started:my_first_tests ), I created a new class project, referenced the other project I wanted to test (another class library), wrote a few tests, then ran them.

Every single one of my tests are really, really simple. And the methods I test are also simple.

Here is an example. The tested function :

    Public Shared Function IsBool(ByVal data As Object) As Boolean
        Dim retour As Boolean = True
        Try
            If data.ToString IsNot Nothing Then
                If data.ToString = "1" Or data.ToString = "0" Then
                    retour = True
                Else
                    Boolean.Parse(data.ToString)
                End If

            End If

        Catch ex As Exception
            retour = False
        End Try

        Return retour
    End Function

And the test :

    <Test()> _
    Public Sub IsBool_trueString()
        Dim result As Boolean = IsBool("true")
        Assert.AreEqual(True, result)
    End Sub

And the error :

System.TypeInitializationException: Une exception a été levée par l'initialiseur de type pour 'CMS.Utility'. ---> System.NullReferenceException: La référence d'objet n'est pas définie à une instance d'un objet.
   à CMS.Utility..cctor() dans C:\...\Utility.vb:ligne 12
   --- End of inner exception stack trace ---
TypeName: CMS.Utility
   à CMS.Utility.IsBool(Object data)
   à KoamaOPTests.CMS.Tests.Utility.IsBool_trueString() dans C:\...\Tests\Utility.vb:ligne 34

I realise there should be no such exception with a shared method, which is why it has me very, very confused.

Thanks


Solution

  • Your static/shared method IsBool is part of the class CMS.Utility which has most probably a static constructor (around line 12 in Utility.vb).

    Static constructors are called once before the type can be used for the first time (that is before IsBool is even executed). It seems that there is bug in it which causes a null reference exception. Can you post the code of the method near the line 12?