Created
June 20, 2022 22:11
-
-
Save hartmark/93bcb58e8cafa6ab417dc4ff397ee2c4 to your computer and use it in GitHub Desktop.
Extract calling details from NSubstitute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CallingTest | |
{ | |
private readonly ITestOutputHelper testOutputHelper; | |
private readonly AwesomeService awesomeService; | |
private readonly IDependantService dependantServiceMock; | |
public CallingTest(ITestOutputHelper testOutputHelper) | |
{ | |
this.testOutputHelper = testOutputHelper; | |
dependantServiceMock = Substitute.For<IDependantService>(); | |
awesomeService = new AwesomeService(dependantServiceMock); | |
} | |
[Fact] | |
public void DoAwesomeStuff_ShouldCallDependantServiceWithCorrectParamters() | |
{ | |
awesomeService.DoAwesomeStuff(); | |
testOutputHelper.WriteLine(dependantServiceMock.ReceivedCallsDetails().ToJson(true)); | |
testOutputHelper.WriteLine(dependantServiceMock.ReceivedCallsArguments().ToJson(true)); | |
} | |
} | |
public static class SubstituteExtension | |
{ | |
public static IEnumerable ReceivedCallsDetails<T>(this T substitute) where T : class | |
{ | |
return substitute.ReceivedCalls().Select(ReceivedCallsDetails); | |
} | |
private static IEnumerable ReceivedCallsDetails(ICall receivedCall) | |
{ | |
yield return new | |
{ | |
FunctionDefinition = receivedCall.GetMethodInfo().ToString(), | |
FunctionName = receivedCall.GetMethodInfo().Name, | |
Arguments = receivedCall.GetArguments(), | |
ArgumentTypes = receivedCall.GetParameterInfos().Select(x => x.ParameterType.Name) | |
}; | |
} | |
public static IEnumerable ReceivedCallsArguments<T>(this T substitute) where T : class | |
{ | |
return substitute.ReceivedCalls().Select(ReceivedCallsArguments); | |
} | |
private static object[] ReceivedCallsArguments(ICall receivedCall) | |
{ | |
return receivedCall.GetArguments(); | |
} | |
} | |
public interface IDependantService | |
{ | |
decimal FunctionWithManyParameters(int alpha, string beta, long gamma); | |
} | |
public class AwesomeService | |
{ | |
private readonly IDependantService dependantService; | |
public AwesomeService(IDependantService dependantService) | |
{ | |
this.dependantService = dependantService; | |
} | |
public void DoAwesomeStuff() | |
{ | |
dependantService.FunctionWithManyParameters(23, "hej", 9000); | |
dependantService.FunctionWithManyParameters(6, "bla bla", 42); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test output: