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:and then somehow pass
processTD.Objectto your System Under Test (SUT).The
processTD.Objectobject will be a particular implementation ofIProcesswith 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 theIProcessinterface.This (simplified) line of code in the current SUT:
creates and returns a
Processobject. TheProcessclass also implements theIProcessinterface, but it is not a Moq object, and neither can you change it to become a Moq object as long as younewit up asProcess.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
IProcessobject with another.A common way to do that is via Dependency Injection, but you could also use a design pattern like Factory Method.