.NET interface and implementation generator for static members.
This library is useful in case you want to have possibilities to mock static classes or static members in your tests.
- .NET 6 and higher
Stinim
should be associated with the words: static, interface, implementation,Gen
- generator.- Static (also const) fields are converted to the properties.
- Static events, properties and methods are converted to the events, properties and methods respectively.
- All instance (non-static) members are ignored.
Use any approach you prefer to install the NuGet package Tum4ik.StinimGen
.
Declare your interface for a type you want to make mockable, use IIForAttribute
to specify the type to wrap
and the name of the wrapper class to be generated.
using Tum4ik.StinimGen.Attributes;
[IIFor(typeof(DateTime), WrapperClassName = "DateTimeWrapper")]
internal partial interface IDateTime
{
}
Register the declared interface and the generated wrapper class in the DI container.
container.Register<IDateTime, DateTimeWrapper>();
Inject and use your wrapper in any place you need.
internal class MyService
{
private readonly IDateTime _dateTime;
public MyService(IDateTime dateTime)
{
_dateTime = dateTime;
}
public DateTime GetCurrentDateTime()
{
return _dateTime.Now;
}
}
Now you are able to mock the functionality as usual.
using Moq;
using Xunit;
public class MyServiceTests
{
private readonly Mock<IDateTime> _dateTimeMock = new()
private readonly MyService _testeeService;
public MyServiceTests()
{
_testeeService = new(_dateTimeMock.Object);
}
[Fact]
internal void GetCurrentDateTimeTest()
{
var now = DateTime.Now;
_dateTimeMock.Setup(dt => dt.Now).Returns(now);
Assert.Equal(now, _testeeService.GetCurrentDateTime());
}
}
Property | Default | Description |
---|---|---|
sourceType (constructor required) | - | The type to generate interface members and an implementation wrapper for |
WrapperClassName (required) | - | The implementation wrapper class name to generate |
IsPublic | false | Controls the generated implementation wrapper accessibility: true emits public access modifier, false - internal |
IsSealed | true | Controls the ability to inherit generated implementation wrapper: true emits sealed modifier, false - nothing |
IsPartial | false | Control the ability to extend the generated implementation wrapper with custom members: true emits partial keyword, false - nothing |
It may be possible you want to extend the declared interface with your own members and provide their implementations
in the generated wrapper. For that you need to use IsPartial
property.
using Tum4ik.StinimGen.Attributes;
[IIFor(typeof(DateTime), WrapperClassName = "DateTimeWrapper", IsPartial = true)]
internal partial interface IDateTime
{
DateTime Yesterday { get; }
DateTime Tomorrow { get; }
}
partial class DateTimeWrapper
{
public DateTime Yesterday => DateTime.Now.Subtract(TimeSpan.FromDays(1));
public DateTime Tomorrow => DateTime.Now.AddDays(1);
}