I have a service class I'm trying to test and I'm hitting some difficulties
This class has a private constructor so it necessitate to be created from the static Instance property returning a Lazy _singleton value.
public class MyService : IMyService
{
private static readonly Lazy<IMyService> _singleton = new Lazy<IMyService>(() => new MyService(new InjectedService()));
public static IPermissionService Instance = _singleton.Value;
private readonly IInjectedService _injectedService;
private MyService(IInjectedService injectedService) => _injectedService = injectedService;
// instance method I want to test
public void DoSomething()
{
}
}
I'm trying to use AutoFixture and AutoMoq to create my object, using the Create() method, but it keeps complaining I have no public constructor. If I set this constructor public, I still get an error that seems to come from the Lazy func.
Could anyone help? I'm probably having different kind of design issues. I don't know if it can be fixed easily.
Edit 1: I don't have any IoC container so I can register my service as a singleton. I was trying to use this method to simulate an injection of the dependency service so I can write tests with mocks.
I have made some progress, but I'm not sure I like it either... Anyway I'll share what I have
public static class My
{
private static readonly Lazy<IMyService> _singleton = new Lazy<IMyService>(() => new MyService(new InjectedService()));
public static IPermissionService Service = _singleton.Value;
}
public class MyService : IMyService
{
private readonly IInjectedService _injectedService;
public MyService(IInjectedService injectedService) => _injectedService = injectedService;
// instance method I want to test
public void DoSomething()
{
}
}
This way I can build my class with AutoFixture and Freeze a mock of the injectedService.
And I can use the static class this way
My.Service.DoSomething();
And in my tests
Fixture.Freeze<Mock<IInjectedService>>().Setup(...);
var service = Fixture.Create<MyService>();
service.DoSomething();
// assert my things