Я пишу модульный тест для метода, который должен поймать unauperizedAccessexception и вернуть специальный результат перечисления. Тем не менее, тест не сбои-метод возвращает успех вместо unauthorizedAccess .
[Theory]
[AutoData]
internal void GetDirectoryContent_WithNoAccess_ReturnUnauthorizedAccess(string directory)
{
//Arrange
A.CallTo(() => _directoryProxy.EnumerableDirectories(directory))
.Throws();
A.CallTo(() => _directoryProxy.EnumerateFiles(directory))
.Throws();
A.CallTo(() => _directoryProxy.Exists(directory))
.Returns(true);
var systemUnderTests = new Explorer(_loggerStub, _options, _directoryProxy);
//Act
var result = systemUnderTests.GetDirectoryContent(new FileEntity(directory, IsDirectory: true));
//Assert
result.Result.Should().Be(ExplorerResult.UnauthorizedAccess); // FAILS - returns Success
//If I try to get result.Entites will be get UnautorizedAccessException that I cauth in the explorer method
}
< /code>
класс в разделе «Тесты < /p>
internal sealed class Explorer(
ILogger logger,
IOptions explorerOptions,
IDirectoryProxy directoryProxy) : IExplorer
{
private const string LogicalDriveIsNotExistsLogMessage = "Logical drive: {drive} is not exists but was loaded, user possible has linux distro in dual-boot";
private const string GotDirectoryContentLogMessage = "Got {directory} content for {times} nanoseconds";
private const string LoadingAdditionalContentForLogicalDrives = "Loading additional content {path} for logical drives";
private const string DirectoryDoesNotExistLogMessage = "Directory {path} does not exists";
public (IEnumerable Entities, ExplorerResult Result) GetDirectoryContent(FileEntity entity)
{
var stopwatch = Stopwatch.StartNew();
var result = GetDirectoryContentWithoutTimer(entity);
stopwatch.Stop();
logger.LogDebug(GotDirectoryContentLogMessage, entity.Path, stopwatch.Elapsed.Nanoseconds);
return result;
}
private bool IsRootDirectory(string directoryPath) =>
directoryPath == explorerOptions.Value.RootDirectory;
private IEnumerable GetLogicalDrives()
{
foreach (var drive in directoryProxy.GetLogicalDrives())
{
if (IsLinuxLogicalDrive(drive))
{
logger.LogError(LogicalDriveIsNotExistsLogMessage, drive);
continue;
}
yield return new FileEntity(drive, IsDirectory: true);
}
foreach (var fileEntity in AddAdditionalLogicalDrivesContent())
yield return fileEntity;
}
private IEnumerable AddAdditionalLogicalDrivesContent() =>
explorerOptions.Value.RootDirectoryAdditionalContent
.Select(content =>
{
var path = Environment.ExpandEnvironmentVariables(content);
logger.LogDebug(LoadingAdditionalContentForLogicalDrives, path);
return new FileEntity(path, IsDirectory: true);
});
private IEnumerable GetDirectoryContentLazy(string path)
{
foreach (var directory in directoryProxy.EnumerableDirectories(path))
yield return new FileEntity(directory, IsDirectory: true);
foreach (var file in directoryProxy.EnumerateFiles(path))
yield return new FileEntity(file, IsDirectory: false);
}
private (IEnumerable, ExplorerResult) GetDirectoryContentWithoutTimer(FileEntity entity)
{
if (!entity.IsDirectory)
return ([], ExplorerResult.NotDirectory);
try
{
if (IsRootDirectory(entity.Path))
return (GetLogicalDrives(), ExplorerResult.Success);
if (!directoryProxy.Exists(entity.Path))
{
logger.LogError(DirectoryDoesNotExistLogMessage, entity.Path); //user renamed directory that shown in explorer view and try to open it
return ([], ExplorerResult.UnexistingDirectory);
}
return (GetDirectoryContentLazy(entity.Path), ExplorerResult.Success);
}
catch (UnauthorizedAccessException)
{
return ([], ExplorerResult.UnauthorizedAccess);
}
}
private bool IsLinuxLogicalDrive(string drive) => !directoryProxy.Exists(drive);
}
``
Подробнее здесь: https://stackoverflow.com/questions/797 ... teasy-test
UnaultorizedAccessException не попадает в тест FakeIteasy ⇐ C#
Место общения программистов C#
-
Anonymous
1759072780
Anonymous
Я пишу модульный тест для метода, который должен поймать unauperizedAccessexception и вернуть специальный результат перечисления. Тем не менее, тест не сбои-метод возвращает успех вместо unauthorizedAccess .
[Theory]
[AutoData]
internal void GetDirectoryContent_WithNoAccess_ReturnUnauthorizedAccess(string directory)
{
//Arrange
A.CallTo(() => _directoryProxy.EnumerableDirectories(directory))
.Throws();
A.CallTo(() => _directoryProxy.EnumerateFiles(directory))
.Throws();
A.CallTo(() => _directoryProxy.Exists(directory))
.Returns(true);
var systemUnderTests = new Explorer(_loggerStub, _options, _directoryProxy);
//Act
var result = systemUnderTests.GetDirectoryContent(new FileEntity(directory, IsDirectory: true));
//Assert
result.Result.Should().Be(ExplorerResult.UnauthorizedAccess); // FAILS - returns Success
//If I try to get result.Entites will be get UnautorizedAccessException that I cauth in the explorer method
}
< /code>
класс в разделе «Тесты < /p>
internal sealed class Explorer(
ILogger logger,
IOptions explorerOptions,
IDirectoryProxy directoryProxy) : IExplorer
{
private const string LogicalDriveIsNotExistsLogMessage = "Logical drive: {drive} is not exists but was loaded, user possible has linux distro in dual-boot";
private const string GotDirectoryContentLogMessage = "Got {directory} content for {times} nanoseconds";
private const string LoadingAdditionalContentForLogicalDrives = "Loading additional content {path} for logical drives";
private const string DirectoryDoesNotExistLogMessage = "Directory {path} does not exists";
public (IEnumerable Entities, ExplorerResult Result) GetDirectoryContent(FileEntity entity)
{
var stopwatch = Stopwatch.StartNew();
var result = GetDirectoryContentWithoutTimer(entity);
stopwatch.Stop();
logger.LogDebug(GotDirectoryContentLogMessage, entity.Path, stopwatch.Elapsed.Nanoseconds);
return result;
}
private bool IsRootDirectory(string directoryPath) =>
directoryPath == explorerOptions.Value.RootDirectory;
private IEnumerable GetLogicalDrives()
{
foreach (var drive in directoryProxy.GetLogicalDrives())
{
if (IsLinuxLogicalDrive(drive))
{
logger.LogError(LogicalDriveIsNotExistsLogMessage, drive);
continue;
}
yield return new FileEntity(drive, IsDirectory: true);
}
foreach (var fileEntity in AddAdditionalLogicalDrivesContent())
yield return fileEntity;
}
private IEnumerable AddAdditionalLogicalDrivesContent() =>
explorerOptions.Value.RootDirectoryAdditionalContent
.Select(content =>
{
var path = Environment.ExpandEnvironmentVariables(content);
logger.LogDebug(LoadingAdditionalContentForLogicalDrives, path);
return new FileEntity(path, IsDirectory: true);
});
private IEnumerable GetDirectoryContentLazy(string path)
{
foreach (var directory in directoryProxy.EnumerableDirectories(path))
yield return new FileEntity(directory, IsDirectory: true);
foreach (var file in directoryProxy.EnumerateFiles(path))
yield return new FileEntity(file, IsDirectory: false);
}
private (IEnumerable, ExplorerResult) GetDirectoryContentWithoutTimer(FileEntity entity)
{
if (!entity.IsDirectory)
return ([], ExplorerResult.NotDirectory);
try
{
if (IsRootDirectory(entity.Path))
return (GetLogicalDrives(), ExplorerResult.Success);
if (!directoryProxy.Exists(entity.Path))
{
logger.LogError(DirectoryDoesNotExistLogMessage, entity.Path); //user renamed directory that shown in explorer view and try to open it
return ([], ExplorerResult.UnexistingDirectory);
}
return (GetDirectoryContentLazy(entity.Path), ExplorerResult.Success);
}
catch (UnauthorizedAccessException)
{
return ([], ExplorerResult.UnauthorizedAccess);
}
}
private bool IsLinuxLogicalDrive(string drive) => !directoryProxy.Exists(drive);
}
``
Подробнее здесь: [url]https://stackoverflow.com/questions/79777381/unauthorizedaccessexception-not-being-caught-in-fakeiteasy-test[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия