Another alternative is to give the worker a factory method that will create the service:
public class Worker
{
private Func<int, IService> createService;
public Worker(Func<int, IService> createService)
{
this.createService = createService;
}
Then the worker can do:
void DoSomething()
{
var theList = new List<IService>();
for (int i = 1; i <= 3; i++)
{
IService s = createService(i); // Invoke the provided factory method
theList.Add(s);
}
// do something with the list...
}
and the unit test can create the worker like so:
public void SomeTestMethod()
{
var worker = new Worker(CreateMockService);
}
private IService CreateMockService(int arg)
{
return new Mock(arg);
}
The production code would provide a factory method creating real services.