I have an interface that looks like this…
public interface ITempFileNameBuilder
{
string DirectoryPath { get; }
string FileName { get; }
void GenerateNewFileName();
}
… and I want to mock the GenerateNewFileName method so that it sets the FileName property to something new. I know this is an odd request because obviously there is no set defined in the interface because it’s declared as private set; in the two implementations. I did that so you must call GenerateNewFileName to set the FileName property to something new.
Is this possible?
Edit
Here is the unit of work I’m trying to test.
public void StartRecording(string claimNo, string ip_no, string ip_name, IWaveIn input, Stream writer)
{
if (this.IsRecording)
{
return;
}
if (_input != null)
{
_input.Dispose();
}
_input = input;
_input.WaveFormat = _waveFormat;
_input.DataAvailable += (s, args) =>
{
_writer.Write(args.Buffer, 0, args.BytesRecorded);
byte[] buffer = args.Buffer;
for (int index = 0; index < args.BytesRecorded; index += 2)
{
short sample = (short)((buffer[index + 1] << 8) | buffer[index + 0]);
float sample32 = sample / 32768f;
_aggregator.Add(sample32);
}
OnDataAvailable(args);
};
_input.RecordingStopped += (s, args) =>
{
_input.Dispose();
_writer.Dispose();
OnRecordingStopped(args);
};
if (this.CurrentRecording != null)
{
_tempFileNameBuilder.GenerateNewFileName();
}
this.Recordings.Add(new RecordingTrack(claimNo, ip_no, ip_name,
_tempFileNameBuilder.FileName,
_recordingDeployer,
_recordingCompressor));
if (this.MicrophoneLevel == default(float))
{
this.MicrophoneLevel = .75f;
}
_aggregator.Reset();
_writer = writer;
_input.StartRecording();
this.IsRecording = true;
}
And the goal of this unit test is to ensure that the FileName of the CurrentRecording and LastRecording are in fact different. It’s a regression test based on a bug we found earlier. The bug was happening because the FileName property on the RecordingTrack was not being set but rather was just returning the current FileName from the ITempFileNameBuilder instance and so the idea is to ensure that GenerateNewFileName was called and ensure that the set for the TempFileName on the recording track was called.
However, the set on the TempFileName on the RecordingTrack is private too, it’s done in the constructor, so maybe this isn’t really a unit test and more so an integration test?
You’re mocking the interface, not the implementation. So you should care about how the caller interacts with this. If you expect them to call
GenerateNewFileName()and then accessFileName, just expect those two calls and give back the appropriate results (where the “generated” filename can just be anything).There’s no “field” to set here – you’re just talking about an API.
Of course, you could easily create a fake instead of a mock, and use that instead.