FileSystemWatcher在集成测试中没有引发事件?

时间:2012-08-17 18:25:47

标签: events integration-testing mstest filesystemwatcher

我正在尝试对我的类运行集成测试,以确保我希望引发的事件被提升:

    'integration test not unit test
<TestMethod()>
Public Sub Change_Network_File_Causes_Event_To_Be_Raised()
    Dim EventCalled As Boolean
    Dim deployChk = New TRSDeploymentCheck("foo")
    deployChk._localFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameLocalGUIDFile.txt")
    AddHandler deployChk.DeploymentNeeded, Sub() EventCalled = True
    deployChk.NetworkFileLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameNetGUIDFile.txt")
    ChangeNetworkFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameNetGUIDFile.txt"))
    Assert.IsTrue(EventCalled)


End Sub

以下是我在班级中设置FileSystemWatcher对象的方法:

    Friend Property NetworkFileLocation As String
    Set(value As String)
        _netFileLoc = value
        If File.Exists(value) Then
            _watcher = New FileSystemWatcher(value.Replace(Path.GetFileName(value), String.Empty))
            _watcher.EnableRaisingEvents = True
            AddHandler _watcher.Changed, AddressOf OnNetworkFileChanged
        End If
    End Set
    Get
        Return _netFileLoc
    End Get
End Property  

Private Sub OnNetworkFileChanged(source As Object, e As FileSystemEventArgs)
    If IsDeploymentNeeded() Then RaiseEvent DeploymentNeeded()
End Sub

我在 OneNetworkFileChange 子中放了一个断点。断点永远不会被击中。我已验证文件实际上是在 ChangeNetworkFile 中进行了更改我甚至复制了代码(硬编码路径除外)并将其复制到我在单元测试期间运行的Windows应用程序中。它在我的Windows应用程序中工作。我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

经过一些测试后终于弄明白了。事实上,EventCalled永远不会是真的,因为测试的“Windows消息泵”被阻止了。该事件将被解雇,但仅在测试完成后(当然是迟到)。那么你如何解决它?它有点乱,我不喜欢它,但我引用了System.Windows.Forms.dll&amp;叫Application.DoEvents()

        'integration test not unit test
<TestMethod()>
Public Sub Change_Network_File_Causes_Event_To_Be_Raised()
    Dim EventCalled As Boolean
    Dim deployChk = New TRSDeploymentCheck("foo")
    deployChk._localFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameLocalGUIDFile.txt")
    AddHandler deployChk.DeploymentNeeded, Sub() EventCalled = True
    deployChk.NetworkFileLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameNetGUIDFile.txt")
    ChangeNetworkFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameNetGUIDFile.txt"))
    Application.DoEvents()
    Assert.IsTrue(EventCalled)

End Sub

直到有人告诉我一个更好的方法,这似乎是解决方案。

答案 1 :(得分:0)

可能是它的过滤器(string.Empty),它显然只查看没有扩展名的文件(这是一个假设)。

尝试"*.*"或类似的事情:

_watcher = New FileSystemWatcher(value.Replace(Path.GetFileName(value), string.Concat("*.", Path.GetExtension(value))))