Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions PowerKit.Tests/Extensions/CommandExtensionsTests.cs
Comment thread
Tyrrrz marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -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<object?, bool>? canExecute = null, Action<object?>? 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();
}
}
25 changes: 25 additions & 0 deletions PowerKit/Extensions/CommandExtensions.cs
Original file line number Diff line number Diff line change
@@ -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)
{
/// <summary>
/// Executes the command with the specified parameter if it can be executed.
/// </summary>
public void ExecuteIfCan(object? parameter = null)
{
if (command.CanExecute(parameter))
command.Execute(parameter);
}
Comment thread
Tyrrrz marked this conversation as resolved.
}
}
#endif