Assuming an IReader interface, an implementation of the IReader interface ReaderImplementation, and a class ReaderConsumer that consumes and processes data from the reader.
public interface IReader
{
object Read()
}
Implementation
public class ReaderImplementation
{
...
public object Read()
{
...
}
}
Consumer:
public class ReaderConsumer()
{
public string location
// constructor
public ReaderConsumer()
{
...
}
// read some data
public object ReadData()
{
IReader reader = new ReaderImplementation(this.location)
data = reader.Read()
...
return processedData
}
}
For testing ReaderConsumer and the processing I use a mock of IReader. So ReaderConsumer becomes:
public class ReaderConsumer()
{
private IReader reader = null
public string location
// constructor
public ReaderConsumer()
{
...
}
// mock constructor
public ReaderConsumer(IReader reader)
{
this.reader = reader
}
// read some data
public object ReadData()
{
try
{
if(this.reader == null)
{
this.reader = new ReaderImplementation(this.location)
}
data = reader.Read()
...
return processedData
}
finally
{
this.reader = null
}
}
}
In this solution mocking introduces an if sentence for the production code since only the mocking constructor supplies an instances of the interface.
During writing this I realise that the try-finally block is somewhat unrelated since it is there to handle the user changing the location during application run time.
Overall it feels smelly, how might it be handled better?
ReaderConsumer
independent onReaderImplementation
?