I wish to stub all dependencies out in my Rhino.Mocks unit tests, but I end up repeating myself. As the number of dependencies keeps increasing, I need to revisit my existing unit tests and need to add the dependencies. It's unsatisfying and also a signal that I should be doing it in another way.
If I just move initialization to a separate method, I pass into it all the mocks and I have achieved nothing.
Is there a way to initialize and then pass the Using(mocks.Record) into a method as a lambda expression? Or how do you do it?!
Thanks in advance for any comments,
Anders, Denmark
[Test, Category("UnitTest")]
public void TestThatApplicationCanExitByDefault()
{
var mocks = new MockRepository();
var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
var versionProvider = mocks.StrictMock<IVersionProvider>();
var eventAggregator = mocks.StrictMock<IEventAggregator>();
var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
var stateManager = mocks.StrictMock<IStateManager>();
var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();
using (mocks.Record())
{
// constructor fires:
eventAggregator
.Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
.Return(currentWorkspaceChangedEvent);
currentWorkspaceChangedEvent
.Stub(x => x.Subscribe(null))
.IgnoreArguments();
}
var target = new MainWindowViewModel(
workspaceViewModelProvider,
workspaceRepository,
userResponseProvider,
versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);
var canAppExit = target.CanAppExit();
Assert.IsTrue(canAppExit);
mocks.VerifyAll();
}
[Test, Category("UnitTest")]
public void TestThatInsertProjectWorks()
{
var mocks = new MockRepository();
var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
var versionProvider = mocks.StrictMock<IVersionProvider>();
var eventAggregator = mocks.StrictMock<IEventAggregator>();
var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
var stateManager = mocks.StrictMock<IStateManager>();
var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();
var workspaceViewModel = mocks.StrictMock<IWorkspaceViewModel>();
using (mocks.Record())
{
// constructor fires:
eventAggregator
.Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
.Return(currentWorkspaceChangedEvent);
currentWorkspaceChangedEvent
.Stub(x => x.Subscribe(null))
.IgnoreArguments();
workspaceViewModelProvider
.Stub(x => x.GetViewModel())
.Return(workspaceViewModel);
workspaceViewModel
.Stub(x => x.InsertProject());
}
var target = new MainWindowViewModel(
workspaceViewModelProvider,
workspaceRepository,
userResponseProvider,
versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);
target.InsertProject();
mocks.VerifyAll();
}
I tend to have a helper method which is responsible for building my mocks, and this method takes a lambda. The lambda can then communicate the mocks to a test. I have overloads of the test helper method to form an API and thus restrict what mocks are available to the test. In this way mock building can be centralized and so minimize dependency tramping across your tests.
It's more obvious with an example. This uses Moq, but the technique is general.
private static void RunTest(Action<IThing1> test)
{
RunTest(test: (thing1, thing2, thing3) => test(thing1));
}
private static void RunTest(Action<IThing1, IThing2> test)
{
RunTest(test: (thing1, thing2, thing3) => test(thing1, thing2));
}
private static void RunTest(Action<IThing1, IThing2, IThing3> test)
{
IThing1 thing1 = new Mock<IThing1>().Object;
IThing2 thing2 = new Mock<IThing2>().Object;
IThing3 thing3 = new Mock<IThing3>().Object;
test(thing1, thing2, thing3);
}
[Test]
public void do_some_stuff_to_a_thing()
{
RunTest(test: thing1 => {
//Do some testing....
});
}
[Test]
public void do_some_stuff_to_things()
{
RunTest(test: (thing1, thing2) => {
//Do some testing....
});
}
Try using a base class with protected mocked objects and use [SetUp]/[TestFixtureSetUp] (with NUnit for example).
It is wise to put only common objects with initialization to base class - use [SetUp]/[TestFixtureSetUp] in the same class where there are multiple unit tests and you need to mock/initialize something specific only to this tests. Putting everything in your base bloats your unit tests as well (at least they execute longer).
Related
The problem statement looks lengthy but I have tried my best to make it as simple as possible.
I have a small function inside SchedulerLPOP10ReportDataView class which uses DbContext Object as:
public async Task<IEnumerable<T>> GetReportViewData<T>(OneFpsReportsDbContext dbContext)
{
var defaultTimeOut = dbContext.Database.GetCommandTimeout();
dbContext.Database.SetCommandTimeout(new TimeSpan(0,20,0));
var results = await dbContext.VW_Report.FromSqlRaw($"SELECT * from [Analytics].[VW_LPOP10_Report_Scheduling]).ToListAsync();
dbContext.Database.SetCommandTimeout(defaultTimeOut);
return (IEnumerable<T>)(results);
}
The OneFpsReportsDbContext class syntax looks like:
public partial class OneFpsReportsDbContext : DbContext
{
public OneFpsReportsDbContext()
{
}
public OneFpsReportsDbContext(DbContextOptions<OneFpsReportsDbContext> options)
: base(options)
{
}
//code
}
I have written test case as:
[Fact]
public void GetReportViewData_OK()
{
// Arrange
var unitUnderTest = new SchedulerLPOP10ReportDataView(It.IsAny<int>());
var mockSet = new Mock<DbSet<DbContext>>();
var MockOneFpsReportsDbContext1 = new Mock<OneFpsReportsDbContext>();
TimeSpan ts3 = TimeSpan.FromMinutes(20);
MockOneFpsReportsDbContext1.Setup(x => x.Database.SetCommandTimeout(ts3)); //[1] error
//Act
var res = unitUnderTest.GetReportViewData<ISchedularReportDataView>(MockOneFpsReportsDbContext1.Object, WhereClause, sqlParameters).Result;
//Assert
}
At [1] error I get this:
Unsupported expression: ... => ....SetCommandTimeout(ts3) Extension
methods (here: RelationalDatabaseFacadeExtensions.SetCommandTimeout)
may not be used in setup / verification expressions.
I also tried the 'UseInMemoryDatabase' approach but I came to know we can't use 'GetCommandTimeout' with it.
What Am I missing or doing incorrect in the //Arrange section of my test case? And How exactly can I make this mock / work?
Thanks.
This is, unfortunately, one of the hard-to-overcome limitations of XUnit/in-memory DB combo. You basically have two choices:
Spin up an actual test database locally for your unit testing purposes. In this case you'll be closer to production, but your test would kinda turn from unit into integration since you'll lack proper isolation
Create a wrapper class around the DbContext plus extension methods you need and mock that class instead.
The latter will look like this:
public class DbContextWrapper: OneFpsReportsDbContext
{
public void SetCommandTimeout(TimeSpan ts)
{
this.Database.SetCommandTimeout(ts);
}
}
// Then inside the usage block
public async Task<IEnumerable<T>> GetReportViewData<T>(DbContextWrapper dbContext)
{
var defaultTimeOut = dbContext.Database.GetCommandTimeout();
dbContext.SetCommandTimeout(new TimeSpan(0,20,0));
var results = await dbContext.VW_Report.FromSqlRaw($"SELECT * from [Analytics].[VW_LPOP10_Report_Scheduling]").ToListAsync();
dbContext.Database.SetCommandTimeout(defaultTimeOut);
return (IEnumerable<T>)(results);
}
// And in the test:
[Fact]
public void GetReportViewData_OK()
{
// Arrange
var unitUnderTest = new SchedulerLPOP10ReportDataView(It.IsAny<int>());
var mockSet = new Mock<DbSet<DbContext>>();
var MockOneFpsReportsDbContext1 = new Mock<DbContextWrapper>();
TimeSpan ts3 = TimeSpan.FromMinutes(20);
MockOneFpsReportsDbContext1.Setup(x => x.SetCommandTimeout(ts3)); //[1] error
//Act
var res = unitUnderTest.GetReportViewData<ISchedularReportDataView>(MockOneFpsReportsDbContext1.Object, WhereClause, sqlParameters).Result;
//Assert
}
I have created an abstract class that implements Polly that I want to write unit tests for.
In one of my tests I want to test how my method handles certain values of PolicyResult.FinalException.
Because the returned PolicyResult is null I get a NullReferenceException when evaluating result.FinalException
How do I mock the returned result?
What I have so far:
public class AbstractRestClientTest
{
private AbstractRestClient _sut;
private Mock<IRestRequestFactory> _requestFactoryMock;
private Mock<IRestClientFactory> _restClientfactoryMock;
private Mock<IPollyPolicyFactory> _policyFactoryMock;
private Mock<IAsyncPolicy> _policyMock;
private const string DUMMY_URL = "http://dosomething.com/getmesomething";
[SetUp]
public void SetUp()
{
_requestFactoryMock = new Mock<IRestRequestFactory>();
_restClientfactoryMock = new Mock<IRestClientFactory>();
_policyFactoryMock = new Mock<IPollyPolicyFactory>();
var settings = new MockSettings();
_policyMock = new Mock<IAsyncPolicy>();
_policyFactoryMock.Setup(mock =>
mock.CreateAsyncResiliencePolicy(settings))
.Returns(_policyMock.Object);
_sut = new MockRestClient(settings, _restClientfactoryMock.Object,
_policyFactoryMock.Object,
_requestFactoryMock.Object);
}
}
public class MockRestClient : AbstractRestClient
{
public MockRestClient(RestSettings settings, IRestClientFactory restClientFactory, IPollyPolicyFactory pollyPolicyFactory,
IRestRequestFactory requestFactory) : base(settings, restClientFactory, pollyPolicyFactory, requestFactory) {
}
}
public class MockSettings : RestSettings
{
public override string Naam => "TestSettings";
}
------------------ EDIT 1 --------------------------------
With Nkosi's comment I got a little bit further but still PolicyResult returned by _policy.ExecuteAndCaptureAsync is null. This leads me to believe that there is something wrong in the way that I mock that method.
I changed my test to the following but still it returns `null``:
[Test]
public async Task HandleRequest_IfFinalExceptionNotNull_ThenThrowsException()
{
var mockResult = new Mock<IRestResponse<int>>();
PolicyResult<IRestResponse<int>> result = PolicyResult<IRestResponse<int>>.Failure(mockResult.Object, new Context());
//Is the following mock correctly setup?
_policyMock.Setup(mock => mock.ExecuteAndCaptureAsync(It.IsAny<Func<Task<IRestResponse<int>>>>()))
.ReturnsAsync(result);
var url = new Url(DUMMY_URL);
Assert.ThrowsAsync<Exception>(() => _sut.GetResult<int>(url));
}
I evaluated the parameters needed for ExecuteAndCapture and changed my setup for this method accordingly, what am I doing wrong?
Based on the publicly available source code on GitHub, there really is no need to mock that class. While it does have an internal constructor, static factory methods exist that should allow for the creation of your desired instance
For example
Context context = //...created as needed
PolicyResult<TestResponse> result = PolicyResult<TestResponse>.Failure(..., context);
Choose the right combination to satisfy the expected result in your test.
The issue was I was mocking the wrong version of ExecuteAndCaptureAsync, I needed to mock the method with the following signature:
`Task<PolicyResult> ExecuteAndCaptureAsync(Func<CancellationToken, Task> action, CancellationToken cancellationToken);`
So after I changes my SetUp accordingly the test succeeded:
[Test]
public async Task HandleRequest_IfFinalExceptionNotNull_ThenThrowsException()
{
var mockResult = new Mock<IRestResponse<int>>();
PolicyResult<IRestResponse<int>> result = PolicyResult<IRestResponse<int>>.Failure(mockResult.Object, new Context());
_policyMock.Setup(mock => mock.ExecuteAndCaptureAsync(
It.IsAny<Func<CancellationToken, Task<IRestResponse<int>>>>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(result);
var url = new Url(DUMMY_URL);
Assert.ThrowsAsync<Exception>(() => _sut.GetResultaat(url, new CancellationToken()));
}
I'd like to test my logic which expects three different interfaces. How can I unite these, because I can't use mock methods while I have three instances. I guess I did something very wrong with the repositories but I have no idea. Thank you for your help!
[Test]
public void TestThatLogicABCWorks()
{
Mock<IRepositoryA> mockInstance1 = new Mock<IRepositoryA>();
Mock<IRepositoryB> mockInstance2 = new Mock<IRepositoryB>();
Mock<IRepositoryC> mockInstance3 = new Mock<IRepositoryC>();
LogicABC logic = new LogicABC(mockInstance1.Object, mockInstance2.Object, mockInstance3.Object);
}
Edit: i have three entity classes, 1 general repository and three entity specific repos. In logic I make queries including all three entities, which I reach as:
public class LogicABC : ILogic
{
IRepository<A> ARepo; //generic repo
IRepository<B> BRepo;
IRepository<C> CRepo;
public LogicABC(IARepository ARepo, IBRepository BRepo, ICRepository CRepo)
{
this.ARepo = ARepo; //entity specific repos
this.BRepo = BRepo;
this.CRepo = CRepo;
}
public LogicABC()
{
var Entity = new ABCEntities(); //context
this.ARepo = new ARepository(Entity);
this.BRepo = new BRepository(Entity);
this.CRepo = new CRepository(Entity);
}
//queries
public List<int> Query1()
{
var q1 = from x in CRepo.GetAll()
select x.Id;
return q1.ToList();
}
I need to test these queries with mock. For example setup that logicABC.Query1() returns 1 and then verify it.
When testing a subject under test that has dependencies, the dependencies explicitly needed for the test to flow to complete should be provided.
In this case Query1() is only using ICRepository and has not shown any interaction with the other two dependencies. If that is truly the case then those other dependencies are not needed.
Based on the method under test the following assumptions are being made
public interface ICRepository : IRepository<C> {
//...
}
and something similar for the other repositories IARepository and IBRepository.
public interface IRemository<TEntity> {
IEnumerable<TEntity> GetAll();
//...other members
}
public class C {
public int Id { get; set; }
//...other members
}
So the test for Query1 could be done as follows.
[Test]
public void LogicABC_Query1_Should_Return_One_Id() {
//Arrange
int expected = 123456789;
var items = new [] { new C { Id = expectedId } }
Mock<IRepositoryC> mock = new Mock<IRepositoryC>();
mock.Setup(_ => _.GetAll()).Returns(items);
LogicABC logic = new LogicABC(null, null, mock.Object);
//Act
List<int> list = logic.Query1();
//Assert
mock.Verify(_ => _.GetAll(), Times.Once());
//checking expected behavior - using FluentAssertions
list.Should().HaveCount(1);
int actual = list.First();
actual.Should().Be(expected); // using FluentAssertions
}
The unit test above tests the expected behavior of one subject method. The same pattern can be done for other members of the class under test.
You need to mock methods in every repository mock, i.e. in mockInstance1, mockInstance2 and mockInstance3. After this you'll be able to verify behavior inside LogicABC by checking applied mocks for every repos
UPDATE:
Your test should look like this:
[Test]
public void TestThatLogicABCWorks()
{
Mock<IRepositoryA> mockInstance1 = new Mock<IRepositoryA>();
mockInstance1.Setup(foo => foo.Do()).Returns(() => 1);
Mock<IRepositoryB> mockInstance2 = new Mock<IRepositoryB>();
mockInstance2.Setup(boo => boo.Do2()).Returns(() => 2);
Mock<IRepositoryC> mockInstance3 = new Mock<IRepositoryC>();
mockInstance3.Setup(doo => doo.Do3()).Returns(() => 3);
LogicABC logic = new LogicABC(mockInstance1.Object, mockInstance2.Object, mockInstance3.Object);
logic.DoLogic();
// do some asserts here
}
Shown below are the class and the method in the test class. The test method is for testing during the state that a monitoring request is published. The expected action is that the handler is called inside the FzrteMonitoringService class.
Here, I am trying to verify whether the handler for the monitoringRequestGenerated event is called inside the FzrteMonitoringService class. But the problem is that the class Dependency is a dependency, and I trying to figure out how to write the FzrteMonitoringService class to avoid such a dependency. The Dependency class is a class that works with MEF to resolve instances exported with the Export attribute. An architect was responsible for its design. Replacing the Dependency class with a TestDependency class for tests seems like an idea, but how would it create instances?
[ImportingConstructor]
public FzrteMonitoringService(IEventAggregator inEventAggregator)
{
_eventAggregator = inEventAggregator;
_monitoringRequestExecutor = Dependency.Resolve<IFzrteMonitoringRequestResponseHandler>();
WatchedPorts = new List<string>();
FailedAddWatchRequests = new List<MonitoringRequest>();
_monitoringRequests = new ConcurrentQueue<FzrteMonitoringRequest>();
//subsription for monitoring requests on the UI thread to limit the user
//from generating meaningless requests
_eventAggregator.GetEvent<MonitoringRequestGenerated>()
.Subscribe(FilterEventType, ThreadOption.UIThread, true);
}
[Test]
[Category("Simple Basic Tests")]
public void SubscribesToMonitoringRequets_requestPublished_FilterEventTypeCalled()
{
//mock of event aggregator and the request event dependencies of monitoring service
var mockEventAggregator = new Mock<IEventAggregator>();
var mockMonitoringRequestedEvent = new Mock<MonitoringRequestGenerated>();
mockEventAggregator.Setup(x => x.GetEvent<MonitoringRequestGenerated>())
.Returns(mockMonitoringRequestedEvent.Object);
Action <List<MonitoringRequest>> callbackMethod = null;
mockMonitoringRequestedEvent.Setup(x => x.Subscribe(
It.IsAny<Action<List<MonitoringRequest>>>(),
It.IsAny<ThreadOption>(),
It.IsAny<bool>(),
It.IsAny<Predicate<List<MonitoringRequest>>>())).
Callback<Action<List<MonitoringRequest>>,
ThreadOption,
bool,
Predicate<List<MonitoringRequest>>>((a, t, b, p) => callbackMethod = a);
var testFzrteMonitoringService = new FzrteMonitoringService(mockEventAggregator.Object);
//use the actual event aggregator to publish
var mockMonitoringRequestEventPayload = new Mock<List<MonitoringRequest>>();
mockEventAggregator.Object.GetEvent<MonitoringRequestGenerated>().Publish(mockMonitoringRequestEventPayload.Object);
mockMonitoringRequestedEvent.Verify(x => x.Subscribe(testFzrteMonitoringService.FilterEventType));
}
It's not really clear what exactly you're trying to test, looking on a code you've provided, but I'll try to address your question.
The main problem with Dependency class is that it's static (or probably its Resolve<> method). You should try to abstract it via introducing IDependency interface
public interface IDependency
{
T Resolve<T>();
}
so you can inject it into your service and then mock it in your tests.
After this simple refactoring your service's constructor will look like this:
[ImportingConstructor]
public FzrteMonitoringService(
IEventAggregator inEventAggregator,
IDependency dependency)
{
_eventAggregator = inEventAggregator;
_dependency = dependency;
_monitoringRequestExecutor = dependency.Resolve<IFzrteMonitoringRequestResponseHandler>();
WatchedPorts = new List<string>();
_monitoringRequests = new ConcurrentQueue<FzrteMonitoringRequest>();
//subsription for monitoring requests on the UI thread to limit the user
//from generating meaningless requests
_eventAggregator.GetEvent<MonitoringRequestGenerated>()
.Subscribe(this.FilterEventType, ThreadOption.UIThread, true);
}
and your test:
[Test]
[Category("Simple Basic Tests")]
public void SubscribesToMonitoringRequets_requestPublished_FilterEventTypeCalled()
{
//mock of event aggregator and the request event dependencies of monitoring service
var mockEventAggregator = new Mock<IEventAggregator>();
var mockMonitoringRequestedEvent = new Mock<MonitoringRequestGenerated>();
var mockDependecy = new Mock<IDependency>();
mockEventAggregator.Setup(x => x.GetEvent<MonitoringRequestGenerated>())
.Returns(mockMonitoringRequestedEvent.Object);
Action<List<MonitoringRequest>> callbackMethod = null;
mockMonitoringRequestedEvent
.Setup(
x => x.Subscribe(
It.IsAny<Action<List<MonitoringRequest>>>(),
It.IsAny<ThreadOption>(),
It.IsAny<bool>(),
It.IsAny<Predicate<List<MonitoringRequest>>>()))
.Callback<Action<List<MonitoringRequest>>, ThreadOption, bool, Predicate<List<MonitoringRequest>>>(
(a, t, b, p) => callbackMethod = a);
var testFzrteMonitoringService = new FzrteMonitoringService(
mockEventAggregator.Object, mockDependecy.Object);
//use the actual event aggregator to publish
var mockMonitoringRequestEventPayload = new Mock<List<MonitoringRequest>>();
mockEventAggregator.Object
.GetEvent<MonitoringRequestGenerated>()
.Publish(mockMonitoringRequestEventPayload.Object);
mockMonitoringRequestedEvent.Verify(
x => x.Subscribe(testFzrteMonitoringService.FilterEventType));
}
Though it may not work properly, but the main idea is there.
I'm new to AutoFixture and am trying to create a friendly extension on my test context for the less TDD-inclined devs in the team. Here is the code:
public class HomeController : Controller
{
private readonly ISomeService _someService;
public HomeController(ISomeService someService)
{
_someService = someService;
}
public ActionResult Index()
{
_someService.SomeMethod();
return View("Index");
}
}
public class ControllerContext<T> where T : Controller
{
protected static T ControllerUnderTest;
private static IFixture _fixture;
public ControllerContext()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
_fixture.Customize<ControllerContext>(c => c.Without(x => x.DisplayMode));
ControllerUnderTest = _fixture.Create<T>();
}
protected static Mock<TDouble> For<TDouble>() where TDouble : class
{
//var mock = _fixture.Create<TDouble>();
var mock = _fixture.Create<Mock<TDouble>>();
return mock;
}
}
So the extension is the For method - When I inspect ControllerUnderTest which has an injected 'ISomeService' it has an instance injected just fine, and it definitely calls the method I am asserting against. When I inspect the mock created in the 'For' method it appears to be the same version as the one injected to the controller, but it won't Verify!
public class EXAMPLE_When_going_to_home_page : ControllerContext<HomeController>
{
Because of = () =>
{
ControllerUnderTest.Index();
};
It should_do_something = () =>
{
//This throws a 'Invocation was not performed'
For<ISomeService>().Verify(x => x.SomeMethod());
};
Establish context = () =>
{
};
}
I am struggling to find any examples of someone doing something similar, I know I am definitely doing something stupid here but in my head this test should pass?
Create creates a new anonymous instance every time, unless you froze (via .Freeze<T>() or AutoFixture.Xunit's [Frozen]) an instance. That means that the value that is injected into HomeController is different from the one returned by For.
There are several possible solutions, all of which ultimately will involve Freezing the value or Injecting the one to use.
One example would look like this:
public class ControllerContext<T> where T : Controller
{
private static Lazy<T> _controllerFactory;
private static IFixture _fixture;
public ControllerContext()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
_fixture.Customize<ControllerContext>(c => c.Without(x => x.DisplayMode));
_controllerFactory = new Lazy<T>(() => _fixture.Create<T>());
}
protected static Mock<TDouble> For<TDouble>() where TDouble : class
{
var mock = _fixture.Freeze<Mock<TDouble>>();
return mock;
}
protected static T ControllerUnderTest
{
get { return _controllerFactory.Value; }
}
}
public class EXAMPLE_When_going_to_home_page : ControllerContext<HomeController>
{
static Mock<ISomeService> SomeService;
Because of = () =>
{
SomeService = For<ISomeService>();
ControllerUnderTest.Index();
};
It should_do_something = () =>
{
//This throws a 'Invocation was not performed'
SomeService.Verify(x => x.SomeMethod());
};
Establish context = () =>
{
};
}
The important point of this changed version is that first Freeze is called on the service mock and only after that the anonymous instance of the controller is created. Because of the way the For method is now used, you should probably rename it to GetService.
You'll ultimately end up in a world of pain if you go down the road of having static state as a way of managing the interaction between the services and the SUT. One reason is for example that unit tests should be parallelizable (e.g. xUnit.net v2 but ultimately all test frameworks as it just makes sense)
You can add Customizations to AutoFixture to allow natural creation of MVC Controllers as needed and then it's just a matter of feeding in or Freezing customized dependencies as necessary.
I'd strongly suggest taking the time to change your structure of your tests to have AutoFixture creating the Controller declaratively - have a look at what's possible with AutoFixture.Xunit and use that to inform how you structure the test helpers you're using in your Specs.
(Some background - I've been around the houses with all this Spec stuff using SubSpec and ultimately ended up much happier with AutoFixture.Xunit - it's just simpler and more composable.