Mengejeknya di tingkat yang lebih tinggi dari itu. Buat kelas proxy di sekitar Process.Start()
, berpura-pura bahwa dalam tes dan periksa input.
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
}
}
}
Di mana pun Anda perlu menggunakan ClassUnderTest dalam kode aplikasi, gunakan konstruktor default. Dalam pengujian Anda, berikan FakeProcessProxy ke konstruktor lain, menggunakan parameter Proxy Start yang diharapkan dan hasil tes Anda di konstruktor palsu itu.