In 2023 I have created RSCG_Static as a way to mock static methods from classes ( think DateTime, Environment, Process) . From that time , the interfaces in C# have gained static keyword – so – a little improvement seems necessary .
However, how can you mock a static method from a interface ? The answer is below ….
Let’s start with DateTime.Now ( yes, I know about TimeProvider , but this is not the point) .
I have the following code
public Type GenerateInterfaceFromDate()=>typeof(DateTime);
And I can use a static implementation
public class DateTimeTest : IDateTime
{
public static DateTime Now => new DateTime(1970,4,16);
And the code will be
var time = IDateTime.GetNow<DateTimeTest>(); Console.WriteLine(time.ToString()); time= IDateTime.GetNow<DateTimeImplDefault>(); Console.WriteLine(time.ToString());