I have a C# method I want to mock the return value of in a unit test. My test infrastructure uses Autofac and AutoMock for dependency inversion/injection.
public System.Diagnostics.Abstractions.IProcess GetClientIProcess(int ProcessId)
{
var temp = Process.GetProcessById(ProcessId);
System.Diagnostics.Abstractions.IProcess clientIProcess = new System.Diagnostics.Abstractions.Process(temp);
return clientIProcess;
}
All I want to achieve is to mock the return value here so that it will return a valid IProcess that is used in the real method that I am testing in my unit test
If you want to use Moq to create a Test Double version of IProcess
, you'd create an object in your test code in this way:
var processTD = new Mock<IProcess>();
and then somehow pass processTD.Object
to your System Under Test (SUT).
The processTD.Object
object will be a particular implementation of IProcess
with test-specific behaviour, specified by the test code. Only that object will have that behaviour. This object's concrete type is an auto-emitted class that implements the IProcess
interface.
This (simplified) line of code in the current SUT:
IProcess clientIProcess = new Process(temp);
creates and returns a Process
object. The Process
class also implements the IProcess
interface, but it is not a Moq object, and neither can you change it to become a Moq object as long as you new
it up as Process
.
If you want to test using Moq, you'll have to figure out how to hook into the SUT in a way that enables you to replace one IProcess
object with another.
A common way to do that is via Dependency Injection, but you could also use a design pattern like Factory Method.