Skip to content

Commit

Permalink
Fixed RedundantArgumentMatcherException
Browse files Browse the repository at this point in the history
  • Loading branch information
icalvo committed May 23, 2023
1 parent 055fb2b commit 93e2524
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
9 changes: 8 additions & 1 deletion src/NSubstitute/Arg.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Linq.Expressions;
using NSubstitute.Core;
using NSubstitute.Core.Arguments;
using NSubstitute.Exceptions;

// Disable nullability for client API, so it does not affect clients.
#nullable disable annotations
Expand Down Expand Up @@ -94,7 +96,12 @@ public static ref TDelegate InvokeDelegate<TDelegate>(params object[] arguments)
/// </summary>
public static ref T Do<T>(Action<T> useArgument)
{
if (typeof(T) == typeof(AnyType)) throw new ArgumentException("Use DoForAny() instead of Do<AnyType>()");
if (typeof(T) == typeof(AnyType))
{
SubstitutionContext.Current.ThreadContext.DequeueAllArgumentSpecifications();
throw new DoAnyTypeException();
}

return ref ArgumentMatcher.Enqueue<T>(new AnyArgumentMatcher(typeof(T)), x => useArgument((T) x!));
}

Expand Down
7 changes: 7 additions & 0 deletions src/NSubstitute/Exceptions/DoAnyTypeException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace NSubstitute.Exceptions;

public class DoAnyTypeException : SubstituteException
{
private const string FixedMessage = "Use DoForAny() instead of Do<AnyType>()";
public DoAnyTypeException() : base(FixedMessage) { }
}
8 changes: 3 additions & 5 deletions tests/NSubstitute.Acceptance.Specs/GenericArguments.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using NSubstitute.Exceptions;
using NUnit.Framework;

namespace NSubstitute.Acceptance.Specs;
Expand Down Expand Up @@ -40,11 +40,9 @@ public void Return_result_for_any_argument()
[Test]
public void Throw_with_Do_AnyType()
{
string argDoResult = null;

ISomethingWithGenerics something = Substitute.For<ISomethingWithGenerics>();

Assert.Throws<ArgumentException>(() =>
something.Log(Arg.Any<int>(), Arg.Do<Arg.AnyType>(a => argDoResult = a.ToString())));
Assert.Throws<DoAnyTypeException>(() =>
something.Log(Arg.Any<int>(), Arg.Do<Arg.AnyType>(a => _ = a.ToString())));
}
}

0 comments on commit 93e2524

Please sign in to comment.