Answers:
在更高的水平上进行模拟。在周围创建一个代理类Process.Start()
,在测试中伪造该代理类并检查输入。
public interface IProcessProxy
{
ProcessInfo Start(string application, string[] arguments);
}
public class ProcessProxy : IProcessProxy
{
public ProcessInfo Start(string application, string[] arguments)
{
return Process.Start(application, arguments);
}
}
// You could use a mocking framework for this, but for the purposes
// of this example ...
public class FakeProcessProxy : IProcessProxy
{
private string _expectedApplication;
private string[] _expectedArguments;
private ProcessInfo response;
public FakeProxy(string expectedApplication, string[] expectedArguments, ProcessInfo response)
{
_expectedApplication = expectedApplication;
_expectedArguments = expectedArguments;
}
public ProcessInfo Start(string application, string[] arguments)
{
// compare input to expectations and throw exception if not matching
return _response;
}
}
// You can also use an IoC framework to inject your IProcessProxy, but I won't.
public class ClassUnderTest
{
public ClassUnderTest(IProcessProxy proxy)
{
_proxy = proxy;
}
public ClassUnderTest() : this(new ProcessProxy())
{
}
public void MethodUnderTest()
{
// Do stuff
ProcessInfo process = _proxy.Start(@"C:\Program Files\App\App.exe", new[] { "arg1", "arg2" });
process.WaitForExit();
if (process.ExitCode == 0)
{
// Act on success
}
else
{
// Act on failure
}
}
}
在需要在应用程序代码中使用ClassUnderTest的任何地方,请使用默认构造函数。在您的测试中,使用预期的Proxy Start参数并将测试结果传递到假的构造函数中,将FakeProcessProxy传递给其他构造函数。