diff --git a/PowerKit.Tests/Extensions/CommandExtensionsTests.cs b/PowerKit.Tests/Extensions/CommandExtensionsTests.cs new file mode 100644 index 0000000..4b8f98d --- /dev/null +++ b/PowerKit.Tests/Extensions/CommandExtensionsTests.cs @@ -0,0 +1,52 @@ +using System; +using System.Windows.Input; +using FluentAssertions; +using PowerKit.Extensions; +using Xunit; + +namespace PowerKit.Tests.Extensions; + +file class FakeCommand(Func? canExecute = null, Action? execute = null) + : ICommand +{ + public event EventHandler? CanExecuteChanged + { + add { } + remove { } + } + + public bool CanExecute(object? parameter) => canExecute?.Invoke(parameter) ?? true; + + public void Execute(object? parameter) => execute?.Invoke(parameter); +} + +public class CommandExtensionsTests +{ + [Fact] + public void ExecuteIfCan_Test() + { + // Arrange + var executed = false; + var command = new FakeCommand(_ => true, _ => executed = true); + + // Act + command.ExecuteIfCan(); + + // Assert + executed.Should().BeTrue(); + } + + [Fact] + public void ExecuteIfCan_CannotExecute_Test() + { + // Arrange + var executed = false; + var command = new FakeCommand(_ => false, _ => executed = true); + + // Act + command.ExecuteIfCan(); + + // Assert + executed.Should().BeFalse(); + } +} diff --git a/PowerKit/Extensions/CommandExtensions.cs b/PowerKit/Extensions/CommandExtensions.cs new file mode 100644 index 0000000..746164e --- /dev/null +++ b/PowerKit/Extensions/CommandExtensions.cs @@ -0,0 +1,25 @@ +#if NETSTANDARD || NET +#nullable enable +using System.Diagnostics.CodeAnalysis; +using System.Windows.Input; + +namespace PowerKit.Extensions; + +#if !POWERKIT_INCLUDE_COVERAGE +[ExcludeFromCodeCoverage] +#endif +internal static class CommandExtensions +{ + extension(ICommand command) + { + /// + /// Executes the command with the specified parameter if it can be executed. + /// + public void ExecuteIfCan(object? parameter = null) + { + if (command.CanExecute(parameter)) + command.Execute(parameter); + } + } +} +#endif