Skip to content

Commit

Permalink
Add tests to demonstrate change
Browse files Browse the repository at this point in the history
  • Loading branch information
JMolenkamp committed Jan 28, 2025
1 parent 1fcbcde commit 4a15bfb
Showing 1 changed file with 69 additions and 2 deletions.
71 changes: 69 additions & 2 deletions tests/NSubstitute.Acceptance.Specs/GenericArguments.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Collections;
using NUnit.Framework;
using System.Collections;
using System.Globalization;
using NUnit.Framework;
using System.Reflection;

namespace NSubstitute.Acceptance.Specs;

Expand All @@ -11,6 +12,7 @@ public interface ISomethingWithGenerics
{
void SomeAction<TState>(int level, TState state);
string SomeFunction<TState>(int level, TState state);
ICollection<TState> SomeFunction<TState>(int level);
void SomeActionWithGenericConstraints<TState>(int level, TState state) where TState : IEnumerable<int>;
string SomeFunctionWithGenericConstraints<TState>(int level, TState state) where TState : IEnumerable<int>;
}
Expand Down Expand Up @@ -131,4 +133,69 @@ public void Is_matcher_works_with_AnyType_and_constraints()

Assert.That(result, Is.EqualTo("matched"));
}

[Test]
public void When_Do_works_with_AnyType_for_generic_method_without_generic_parameter()
{
bool whenDoCalled = false;
ISomethingWithGenerics something = Substitute.For<ISomethingWithGenerics>();
something
.When(x => x.SomeFunction<Arg.AnyType>(Arg.Any<int>()))
.Do(x =>
{
whenDoCalled = true;
});

var result = something.SomeFunction<int>(7);

Assert.That(whenDoCalled, Is.True);
}

[Test]
public void Returns_works_with_AnyType_for_generic_method_without_generic_parameter()
{
ISomethingWithGenerics something = Substitute.For<ISomethingWithGenerics>();
something
.SomeFunction<Arg.AnyType>(Arg.Any<int>())
.Returns(x =>
{
return default;
});

var result = something.SomeFunction<int>(7);

// If the Returns call is not made, a substitute would have been returned
Assert.That(result, Is.Null);
}

[Test]
public void Callback_allows_access_to_method_call()
{
static ICollection<T> CreateSubstitute<T>(int count)
{
ICollection<T> substitute = Substitute.For<ICollection<T>>();
substitute.Count.Returns(count);
return substitute;
}

MethodInfo methodInfo = typeof(GenericArguments)
.GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
.Single(x
=> x.Name.Contains(nameof(CreateSubstitute))
&& x.Name.Contains(nameof(Callback_allows_access_to_method_call)));

ISomethingWithGenerics something = Substitute.For<ISomethingWithGenerics>();
something
.SomeFunction<Arg.AnyType>(Arg.Any<int>())
.Returns(x =>
{
Type argumentType = x.MethodInfo.GetGenericArguments()[0];
MethodInfo method = methodInfo.MakeGenericMethod(argumentType);
return method.Invoke(null, [x.Arg<int>()]);
});

ICollection<int> result = something.SomeFunction<int>(7);

Assert.That(result.Count, Is.EqualTo(7));
}
}

0 comments on commit 4a15bfb

Please sign in to comment.