2012-04-26 39 views
0

嗨目前我试图测试更改配置文件失效,测试引发的事件由FileSystemWatcher的

我用下面的代码来做到这一点...

string path = _pathInvalidFormat.Substring(0, _pathInvalidFormat.LastIndexOf('\\')); 
System.IO.File.Copy("TestInvalidXmlConfigurationFile.xml", _pathInvalidFormat, true); 
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(path); 

//catch the invalid file getting deleted 
fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted); 

//catch the temporary config file getting renamed 
fileSystemWatcher.Renamed += new RenamedEventHandler(fileSystemWatcher_Renamed); 
fileSystemWatcher.EnableRaisingEvents = true; 

CreateConfig(_pathInvalidFormat); 
System.Threading.Thread.Sleep(5000); 
Assert.That(_oldFileDeleted); 
Assert.That(_newFileCreated); 
ResetConfig(_pathInvalidFormat); 

不过我不满意这个使用System.Threading.Thread.Sleep(5000);

我试过使用fileSystemWatcher.WaitForChanged(WatcherChangeTypes.Deleted,5000);但似乎无法使其发挥作用,因为它似乎总是达到暂停。即使我看到已删除的事件已被击中,它仍然不会返回。

或者有更好的方式让系统等待异步事件被触发?

感谢

基兰

- 编辑:

我用createconfig(路径)使用下面的方法

private void ReadConfiguration(string path) 
{ 
    var configFileMap = new ExeConfigurationFileMap() 
    { 
     ExeConfigFilename = path, 
    }; 

    // if we try to read bad formatted file let's 
    // 1. delete this file 
    // 2. call read configuration to form correct file 
    try 
    { 
     Config = System.Configuration.ConfigurationManager 
      .OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); 
    } 
    catch (ConfigurationErrorsException) 
    { 
     // ok, there is bad format file, let delete it and create another one 
     // TODO: check security rights? 
     File.Delete(path); 
     ReadConfiguration(path); 
    } 
} 

希望创建一个系统配置文件这给了一些见解至于我的测试试图达到什么目的。

+0

'CreateConfig'是否单独进行线程化?第一个建议是阻止它,除非另有需要。 – 2012-04-26 11:34:39

+0

该方法本身不在单独的线程中,如果有帮助,我添加了CreateConfig调用的代码。 – Kezza 2012-04-26 11:49:01

+0

我假设filewatcher在不同的线程上运行,但是事件异步引发。 – Kezza 2012-04-26 11:52:19

回答

0

将所有代码放入一个函数中,并使用线程异步执行它。

现在,您可以使用线程的手动重置事件在睡眠后执行进一步的代码,此时文件已被删除,重命名并检查了无效路径错误。

以这种方式,代码执行将不会被阻止。

refer this link for example

+0

没有真正解释为什么WaitForChanged方法不起作用,但我已经找到了使用您的答案运行测试的方法,谢谢。 – Kezza 2012-05-23 15:12:50