Skip to content

Commit 0c933c1

Browse files
committed
fixed async handling for when-do
1 parent 86a6a8e commit 0c933c1

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/NSubstitute/Core/WhenCalled.cs

+10
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Threading.Tasks;
12
using NSubstitute.Routing;
23

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

3738
/// <summary>
39+
/// Perform this action when called.
40+
/// </summary>
41+
/// <param name="callbackWithArguments"></param>
42+
public void Do(Func<CallInfo, Task> callbackWithArguments)
43+
{
44+
Do(callInfo => callbackWithArguments(callInfo).GetAwaiter().GetResult());
45+
}
46+
47+
/// <summary>
3848
/// Perform this configured callback when called.
3949
/// </summary>
4050
/// <param name="callback"></param>

tests/NSubstitute.Acceptance.Specs/WhenCalledDo.cs

+24-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
using System;
2+
using System.Threading;
3+
using System.Threading.Tasks;
14
using NSubstitute.Acceptance.Specs.Infrastructure;
25
using NSubstitute.Core;
36
using NUnit.Framework;
@@ -9,11 +12,31 @@ public class WhenCalledDo
912
{
1013
private ISomething _something;
1114

15+
16+
[Test]
17+
public void Execute_when_called_async()
18+
{
19+
var called = false;
20+
_something.When(substitute => substitute.Echo(1)).Do(async info =>
21+
{
22+
await Task.Delay(100);
23+
called = true;
24+
});
25+
26+
Assert.That(called, Is.False, "Called");
27+
_something.Echo(1);
28+
Assert.That(called, Is.True, "Called");
29+
}
30+
1231
[Test]
1332
public void Execute_when_called()
1433
{
1534
var called = false;
16-
_something.When(substitute => substitute.Echo(1)).Do(info => called = true);
35+
_something.When(substitute => substitute.Echo(1)).Do(info =>
36+
{
37+
Thread.Sleep(100);
38+
called = true;
39+
});
1740

1841
Assert.That(called, Is.False, "Called");
1942
_something.Echo(1);

0 commit comments

Comments
 (0)