NUnit无法应对Lazy Instantiation

时间:2018-04-23 14:21:19

标签: vb.net nunit lazy-initialization

我有一个懒惰实例化的单身人士:

Public Class SingletonBase(Of TDerivedClass As {SingletonBase(Of TDerivedClass)})
    Private Shared ReadOnly _instance As New Lazy(Of TDerivedClass)(Function() CType(Activator.CreateInstance(GetType(TDerivedClass), True), TDerivedClass), Threading.LazyThreadSafetyMode.ExecutionAndPublication)

    ''' <summary>
    ''' Using the Singleton pattern allows the config handler to be observable
    ''' </summary>
    ''' <returns></returns>
    Public Shared ReadOnly Property Instance() As TDerivedClass
        Get
            Return _instance.Value
        End Get
    End Property
End Class

然后是实现它的类:

Public MustInherit Class ConfigurationHandlerBase(Of TDerivedConfigHandler As {SingletonBase(Of TDerivedConfigHandler)})
    Inherits SingletonBase(Of TDerivedConfigHandler)

和实现那个的类:

Public Class ConfigHandler
    Inherits ConfigurationHandlerBase(Of ConfigHandler)
    Private _test As String
    Public Shared ReadOnly Property Test as String
        Get
            Return Instance._test
        End Get
    End Property

然后我有一个NUnit项目/类:

Imports NUnit.Framework
<TestFixture>
Public Class ConfigHandlerTests
    <Test>
    Public Sub Test()
        Dim success As ConfigHandler = ConfigHandler.Instance ' this works
        Dim fail as String = ConfigHandler.Test ' this fails!!!

运行测试是NullReferenceException时,我得到的错误,以及调试测试,当它进入属性的Getter时({{ 1}}),将鼠标悬停在Dim test As Boolean = ConfigHandler.Instance._test 有时会出现以下错误:

  

&#39;实例&#39;抛出了#System; Thhreading.ThreadAbortException&#39;

类型的异常

总是如果我尝试进入该行代码,测试将以下面的堆栈跟踪结束:

Instance

我假设Nunit与Result StackTrace: at NUnit.Framework.Internal.Reflect.InvokeMethod(MethodInfo method, Object fixture, Object[] args) at NUnit.Framework.Internal.MethodWrapper.Invoke(Object fixture, Object[] args) at NUnit.Framework.Internal.Commands.TestMethodCommand.RunNonAsyncTestMethod(TestExecutionContext context) at NUnit.Framework.Internal.Commands.TestMethodCommand.RunTestMethod(TestExecutionContext context) at NUnit.Framework.Internal.Commands.TestMethodCommand.Execute(TestExecutionContext context) at NUnit.Framework.Internal.Commands.BeforeAndAfterTestCommand.Execute(TestExecutionContext context) Result Message: Test cancelled by user 玩得不好 - 但有没有人知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

原来我正在吃红鲱鱼。简单的答案是我需要配置项在NUnit项目的配置文件中,而不是主项目。