测试Process.Start?
问题描述:
我正在创建一个应用程序,它将管理外部实用程序的多个实例,为每个实例提供数据并提取结果。测试Process.Start?
但是,当我正在为班级写单元测试时,我遇到了一个问题。
如何测试目标方法在调用时实际启动进程(通过属性设置)?
我曾尝试:
- 使类执行外部程序,然后使用GetProcessesByName检查它是否已经启动。
- 使用输出重定向,例如使用大于号来回显文件并测试它的存在
我觉得发出代码和/或创建另一个exe来测试是矫枉过正。
这是确切的方法:
public void Start()
{
if (!_isRunning) {
var startInfo = new ProcessStartInfo() {
CreateNoWindow = true,
UseShellExecute = true,
FileName = _cmdLine,
Arguments = _args
};
_process = Process.Start(startInfo);
_isRunning = true;
} else {
throw new InvalidOperationException("Process already started");
}
}
我想单元测试,这样,如果没有运行(_isRunning ==假),一个新的进程应催生。
我觉得难倒,有没有一种优雅的方式来单元测试外部过程实际上开始?
答
我会使用依赖注入和使用模拟或伪类来解决这个问题。注意我使用实例方法来启动而不是类方法。在你的常规代码中,你可以使用默认的构造函数,它会为你创建一个过程。对于测试,您可以注入一个模拟或伪造过程,只需检查您的模拟对象上是否调用了正确的方法,而根本不需要真正启动一个过程。您需要对此进行调整,以考虑我省略的属性。防爆。如下:
public class UtilityManager
{
public Process UtilityProcess { get; private set; }
private bool _isRunning;
public UtilityManager() : this(null) {}
public UtilityManager(Process process)
{
this. UtilityProcess = process ?? new Process();
this._isRunning = false;
}
public void Start()
{
if (!_isRunning) {
var startInfo = new ProcessStartInfo() {
CreateNoWindow = true,
UseShellExecute = true,
FileName = _cmdLine,
Arguments = _args
};
this.UtilityProcess.Start(startInfo);
_isRunning = true;
} else {
throw new InvalidOperationException("Process already started");
}
}
测试代码...
[TestMethod]
public void StartTest()
{
Process proc = new FakeProcess(); // May need to use a wrapper class
UtilityManager manager = new UtilityManager(proc);
manager.CommandLine = "command";
...
manager.Start();
Assert.IsTrue(proc.StartCalled);
Assert.IsNotNull(proc.StartInfo);
Assert.AreEqual("command", proc.StartInfo.FileName);
...
}
尼斯...我忽略了StartInfo的分离部分......已经得到解决嘲讽一些我的头...谢谢! – chakrit 2008-12-08 12:36:45