jeudi 19 février 2015

Check if setup already exists for a Moq mock property?

I'm creating a private method in my unit test class that returns the type of mock I need based on optional dependencies I pass in.


Consider the following method under test:



public IEnumerable<ServiceObject> GetSomeData(string query)
{
if (_currentEnvironment.Feeling == Feeling.Cooperative)
{
_dataGetter.GetData(query);
}
}


And a method to create an object with appropriately-setup mocks in my test class:



private DataService GetTestDataService(Mock<ExecutionEnvironment> mockEnvironment = null,
Mock<IDataGetter> mockDataGetter = null)
{
if (mockEnvironment == null)
{
mockEnvironment = new Mock<ExecutionEnvironment>();
}
if (mockDataGetter == null)
{
mockDataGetter = new Mock<IDataGetter>();
}
return new DataService(mockEnvironment.Object, mockDataGetter.Object);
}


I get in a bind when I need to setup the ExecutionEnvironment mock in my tests that need to step into the area where the GetData method is called. I need to have every one of those tests set it up to be feeling cooperative. If clauses are added to the "feeling cooperative" conditional, all of the tests will break until I change the setup in every test. I could create a separate method like CreateDefaultCurrentEnvironmentMock() that does some default setups, so my tests call that, then override the setups where they need to. However, what I'd like to have is all the logic in the same method, which can be accomplished by checking if a setup on the mock already exists, and do a setup if it hasn't been set up yet. Is this possible?


Aucun commentaire:

Enregistrer un commentaire