VS2008 unit tests - output of exit method

I am trying to write a C # unit test using the VS 2008 built-in unit testing system and the method I am testing for calls Environment.Exit(0). When I call this method in my unit test, my unit test is canceled. This method really needs to be called Exit, and I want to test it, and also check the exit code that it uses. How can i do this? I looked at the Microsoft.VisualStudio.TestTools.UnitTesting namespace , but did not see anything that looked relevant.

[TestMethod]
[DeploymentItem("myprog.exe")]
public void MyProgTest()
{
    // Want to ensure this Exit with code 0:
    MyProg_Accessor.myMethod();
}

Meanwhile, here is the gist of the code I want to test:

static void myMethod()
{
    Environment.Exit(0);
}

Edit: here is the solution I used in my test method, thanks to RichardOD :

Process proc;

try
{
    proc = Process.Start(path, myArgs);
}
catch (System.ComponentModel.Win32Exception ex)
{
    proc = null;
    Assert.Fail(ex.Message);
}

Assert.IsNotNull(proc);
proc.WaitForExit(10000);
Assert.IsTrue(proc.HasExited);
Assert.AreEqual(code, proc.ExitCode);
+5
6

. Environment.Exit(0), , , - .

, . Process.Start.

, - .

, - Typemock Isolator - , mock static methods.

+4

Environment, . . RhinoMocks , .

public class EnvironmentWrapper
{
    public virtual void Exit( int code )
    {
        Environment.Exit( code );
    }
}


public class MyClass
{
    private EnvironmentWrapper Environment { get; set; }

    public MyClass() : this( null ) { }

    public MyClass( EnvironmentWrapper wrapper )
    {
        this.Environment = wrapper ?? new EnvironmentWrapper();
    }

    public void MyMethod( int code )
    {
        this.Environment.Exit( code )
    }
}


[TestMethod]
public void MyMethodTest()
{
     var mockWrapper = MockRepository.GenerateMock<EnvironmentWrapper>();

     int expectedCode = 5;

     mockWrapper.Expect( m => m.Exit( expectedCode ) );

     var myClass = new MyClass( mockWrapper );

     myclass.MyMethod( expectedCode );

     mockWrapper.VerifyAllExpectations()
}
+5

- Environment.Exit . , AppDomain, , , .

+3

- Fakie Exit.

+2

, , exit() .

This parameterized method can be extracted from the method called from your application and the unit test of the extracted function. This way you do not have to modify your application.

0
source

The only thing that comes to my mind is something like:

static void myMethod()
{
    DoEnvironmentExit(0);
}

static void DoEnvironentExit(int code)
{
    #if defined TEST_SOLUTION
      SomeMockingFunction(code);
    #else
      Environment.Exit(code);
    #endif
}
0
source

All Articles