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
25 changes: 25 additions & 0 deletions TUnit.Mocks.Assertions/MockAssertionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Runtime.CompilerServices;
using TUnit.Assertions.Attributes;
using TUnit.Assertions.Core;
using TUnit.Mocks.Exceptions;
using TUnit.Mocks.Verification;

namespace TUnit.Mocks.Assertions;
Expand All @@ -10,6 +12,29 @@ namespace TUnit.Mocks.Assertions;
/// </summary>
public static class MockAssertionExtensions
{
/// <summary>
/// Asserts that the mock member was called at least once.
/// Generates the <c>WasCalled()</c> assertion on <see cref="IAssertionSource{ICallVerification}"/>.
/// </summary>
[GenerateAssertion(ExpectationMessage = "to have been called")]
public static AssertionResult WasCalled(ICallVerification verification)
{
if (verification is null)
{
return AssertionResult.Failed("Verification target is null");
}

try
{
verification.WasCalled();
return AssertionResult.Passed;
}
catch (MockVerificationException ex)
{
return AssertionResult.Failed(ex.Message);
}
}

/// <summary>
/// Asserts that the mock member was called the specified number of times.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions TUnit.Mocks.Assertions/TUnit.Mocks.Assertions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<ItemGroup>
<ProjectReference Include="..\TUnit.Mocks\TUnit.Mocks.csproj" />
<ProjectReference Include="..\TUnit.Assertions\TUnit.Assertions.csproj" />
<ProjectReference Include="..\TUnit.Assertions.SourceGenerator\TUnit.Assertions.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>

<Import Project="..\Library.targets" />
Expand Down
24 changes: 24 additions & 0 deletions TUnit.Mocks.Tests/AsyncVerificationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,30 @@ await Assert.That(mock.Add(Any(), Any()))
.WasCalled(Times.AtLeastOnce);
}

[Test]
public async Task WasCalled_AtLeastOnceByDefault_Passes()
{
var mock = ICalculator.Mock();
mock.Add(Any(), Any()).Returns(42);

ICalculator calc = mock.Object;
_ = calc.Add(1, 2);
_ = calc.Add(3, 4);

await Assert.That(mock.Add(Any(), Any()))
.WasCalled();
}

[Test]
public async Task WasCalled_Default_Fails_When_Not_Called()
{
var mock = ICalculator.Mock();

await Assert.ThrowsAsync(async () =>
await Assert.That(mock.Add(Any(), Any()))
.WasCalled());
}

[Test]
public async Task Property_Getter_WasCalled_Via_Assert()
{
Expand Down
Loading