Login
Юнит тесты для "системного" приложения
2301 просмотров
Перейти к просмотру всей ветки
in Antwort AlexNek 15.04.21 12:56
На какой вопрос?
Что ты хочешь тестировать?
Ну вот кусок кода для настройки. Вроде всё верно. А гад реагирует на копирование каталога.
_watcher.Path = directoryName;
// Watch files only.
_watcher.IncludeSubdirectories = false;
// Watch all files.
_watcher.Filter = "*.*";
_watcher.Created += Watcher_Created;
//Start monitoring.
_watcher.EnableRaisingEvents = true;
Это мило, то тут ты конфигурируешь некий объект _watcher. Никакой логики тут нет. Цикломатическая сложность этого кода равна 1.
Но предположим, что ты хочешь получить ошибку (исключение) в момент, когда выполныешь строку _watcher.EnableRaisingEvents = true; если directoryName - директория. И не получать исключение, если directoryName - файл.
В таком случае у тебя есть такой код:
public interface ISystemFile { System.IO.FileAttributes GetAttributes(string path); } public class SystemFile : ISystemFile { public FileAttributes GetAttributes(string path) { return System.IO.File.GetAttributes(path); } } public class FileSystemWatcher { ISystemFile _systemFiles = null; public FileSystemWatcher() : this (new SystemFile()) { } public FileSystemWatcher(ISystemFile systemFiles) { _systemFiles = systemFiles; } public string Path { get; set; } public bool IncludeSubdirectories { get; set; } public string Filter { get; set; } public event EventHandler Created; private bool _enableRaisingEvents = false; public bool EnableRaisingEvents { get { return _enableRaisingEvents; } set { if (value == true) { System.IO.FileAttributes att = _systemFiles.GetAttributes(Path); if (att == System.IO.FileAttributes.Directory) throw new Exception("blah-blah-blah"); } _enableRaisingEvents = value; } } }
Ну и тестируешь то, что надо:
[TestMethod] public void EnableRaisingEvents_TrueForFile_OK() { // Arrenge ISystemFile systemFile = Substitute.For<ISystemFile>(); systemFile.GetAttributes(Arg.Any<string>()).Returns(FileAttributes.Normal); FileSystemWatcher watcher = new FileSystemWatcher(systemFile); // Act watcher.EnableRaisingEvents = true; // Assert Assert.IsTrue (watcher.EnableRaisingEvents); } [TestMethod] [ExpectedException(typeof(Exception))] public void EnableRaisingEvents_TrueForDirectory_Exception() { // Arrenge ISystemFile systemFile = Substitute.For<ISystemFile>(); systemFile.GetAttributes(Arg.Any<string>()).Returns(FileAttributes.Directory); FileSystemWatcher watcher = new FileSystemWatcher(systemFile); // Act watcher.EnableRaisingEvents = true; // Assert }
и какие интересно?
Ну например тоже сделать виртуальную функцию, которая будет возвращать реальную обертку. В тесте такую функцию можно перегрузить.