natemcmaster / CommandLineUtils

Command line parsing and utilities for .NET

Home Page:https://natemcmaster.github.io/CommandLineUtils/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] How do I mock validator.ExistingFile()?

numbworks opened this issue · comments

Hello guys,

first of all, thank you for this amazing library!

Let's say I do have a private method that creates a sub-command for me, such as:

return subCommand
       .Option(Option_JsonPath_Template, Option_JsonPath_Description, CommandOptionType.SingleValue)
       .Accepts(validator => validator.ExistingFile())
       .IsRequired(false, Option_JsonPath_ErrorMessage);

and that I want to unit test its behaviour.

How do I mock ExistingFile()?
Or if not possible, how can I create a validator that checks for the file existance and that I can easily mock?

The scope is to test the behaviour without really writing on disk obviously.

Thank you for your kind help!

The built-in ExistingFile validator doesn't provide a way to mock the filesystem. You will need to write your own validator if you want to do that. You can write your own validators by implementing IOptionValidator. Here's an example of implementing a custom validator:

class MustBeBlueOrRedValidator : IOptionValidator
{
public ValidationResult GetValidationResult(CommandOption option, ValidationContext context)
{
// This validator only runs if there is a value
if (!option.HasValue()) return ValidationResult.Success;
var val = option.Value();
if (val != "red" && val != "blue")
{
return new ValidationResult($"The value for --{option.LongName} must be 'red' or 'blue'");
}
return ValidationResult.Success;
}
}

This issue has been automatically marked as stale because it has no recent activity. It will be closed if no further activity occurs. Please comment if you believe this should remain open, otherwise it will be closed in 14 days. Thank you for your contributions to this project.

Closing due to inactivity.
If you are looking at this issue in the future and think it should be reopened, please make a commented here and mention natemcmaster so he sees the notification.