Unit-testing FileSystemWatcher: how to programmatically trigger a modified event?

I have a FileSystemWatcherdirectory scan for changes, and when there is a new XML file in it, it parses that file and does something with it.

I have some examples of XML files in my project that I use to test modules for the parser I wrote.

I am looking for a way to use sample XML files for testing as well FileSystemWatcher.

Is it possible to program to create an event (somehow related to an XML file) to trigger an event FSW.Changed?

+4
source share
2 answers

I think you're wrong here.

unit test FileSystemWatcher ( - !). :

1) - FileSystemWatcher, FileSystemWatcher. , :

public class FileSystemWatcherWrapper
{
    private readonly FileSystemWatcher watcher;

    public event FileSystemEventHandler Changed;

    public FileSystemWatcherWrapper(FileSystemWatcher watcher)
    {
        this.watcher = watcher
        watcher.Changed += this.Changed;
    }

    public bool EnableRaisingEvents
    {
        get { return watcher.EnableRaisingEvents; }
        set { watcher.EnableRaisingEvents = value; }
    }
}

( , FileSystemWatcher , " " , )

2) :

public interface IFileSystemWatcherWrapper
{
    event FileSystemEventHandler Changed;
    bool EnableRaisingEvents { get; set; }
}

//and therefore...

public class FileSystemWatcherWrapper : IFileSystemWatcherWrapper

3) :

public class TheClassThatActsOnFilesystemChanges
{
    private readonly IFileSystemWatcherWrapper fileSystemWatcher;

    public TheClassThatActsOnFilesystemChanges(IFileSystemWatcherWrapper fileSystemWatcher)
    {
        this.fileSystemWatcher = fileSystemWatcher;

        fileSystemWatcher.Changed += (sender, args) =>
        {
            //Do something...
        };
    }
}

4) :

var theClass = new TheClassThatActsOnFilesystemChanges(
    new FileSystemWatcherWrapper(new FileSystemWatcher()));

5) TheClassThatActsOnFilesystemChanges, IFileSystemWatcherWrapper, ! , Moq.

:

, / , . , , unit test, .

+7

FileSystemWatcher , :

public interface IFileSystemWatcherWrapper : IDisposable
{        
    bool EnableRaisingEvents { get; set; }
    event FileSystemEventHandler Changed;
    //...
}

public class FileSystemWatcherWrapper : FileSystemWatcher, IFileSystemWatcherWrapper
{
    public FileSystemWatcherWrapper(string path, string filter)
        : base(path, filter)
    {
    }
}
+1

Source: https://habr.com/ru/post/1612551/


All Articles