Skip to content

Commit

Permalink
fixed async handling for when-do
Browse files Browse the repository at this point in the history
  • Loading branch information
jmartschinke committed May 7, 2024
1 parent 86a6a8e commit 0c933c1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/NSubstitute/Core/WhenCalled.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Threading.Tasks;
using NSubstitute.Routing;

// Disable nullability for entry-point API
Expand Down Expand Up @@ -35,6 +36,15 @@ public void Do(Action<CallInfo> callbackWithArguments)
}

/// <summary>
/// Perform this action when called.
/// </summary>
/// <param name="callbackWithArguments"></param>
public void Do(Func<CallInfo, Task> callbackWithArguments)
{
Do(callInfo => callbackWithArguments(callInfo).GetAwaiter().GetResult());
}

/// <summary>
/// Perform this configured callback when called.
/// </summary>
/// <param name="callback"></param>
Expand Down
25 changes: 24 additions & 1 deletion tests/NSubstitute.Acceptance.Specs/WhenCalledDo.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using NSubstitute.Acceptance.Specs.Infrastructure;
using NSubstitute.Core;
using NUnit.Framework;
Expand All @@ -9,11 +12,31 @@ public class WhenCalledDo
{
private ISomething _something;


[Test]
public void Execute_when_called_async()
{
var called = false;
_something.When(substitute => substitute.Echo(1)).Do(async info =>
{
await Task.Delay(100);
called = true;
});

Assert.That(called, Is.False, "Called");
_something.Echo(1);
Assert.That(called, Is.True, "Called");
}

[Test]
public void Execute_when_called()
{
var called = false;
_something.When(substitute => substitute.Echo(1)).Do(info => called = true);
_something.When(substitute => substitute.Echo(1)).Do(info =>
{
Thread.Sleep(100);
called = true;
});

Assert.That(called, Is.False, "Called");
_something.Echo(1);
Expand Down

0 comments on commit 0c933c1

Please sign in to comment.