Last active
May 29, 2024 16:26
-
-
Save xpl0t/0d223222696a1c92d7d23cf8368800bf to your computer and use it in GitHub Desktop.
Extension method capable of executing private/public methods on an object
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
using System; | |
using System.Reflection; | |
namespace MyProject.Unit.Tests.Extensions | |
{ | |
public static class ObjectExtensions | |
{ | |
/// <summary> | |
/// Invokes a private/public method on an object. Useful for unit testing. | |
/// </summary> | |
/// <typeparam name="T">Specifies the method invocation result type.</typeparam> | |
/// <param name="obj">The object containing the method.</param> | |
/// <param name="methodName">Name of the method.</param> | |
/// <param name="parameters">Parameters to pass to the method.</param> | |
/// <returns>The result of the method invocation.</returns> | |
/// <exception cref="ArgumentException">When no such method exists on the object.</exception> | |
/// <exception cref="ArgumentException">When the method invocation resulted in an object of different type, as the type param T.</exception> | |
/// <example> | |
/// class Test | |
/// { | |
/// private string GetStr(string x, int y) => $"Success! {x} {y}"; | |
/// } | |
/// | |
/// var test = new Test(); | |
/// var res = test.Invoke<string>("GetStr", "testparam", 123); | |
/// Console.WriteLine(res); // "Success! testparam 123" | |
/// </example> | |
public static T Invoke<T>(this object obj, string methodName, params object[] parameters) | |
{ | |
var method = obj.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); | |
if (method == null) | |
{ | |
throw new ArgumentException($"No private method \"{methodName}\" found in class \"{obj.GetType().Name}\""); | |
} | |
var res = method.Invoke(obj, parameters); | |
if (res is T) | |
{ | |
return (T)res; | |
} | |
throw new ArgumentException($"Bad type parameter. Type parameter is of type \"{typeof(T).Name}\", whereas method invocation result is of type \"{res.GetType().Name}\""); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment