Antiohia Antiohia - 9 days ago 6
C# Question

Test Environment.Exit() in C#

Is there in C# some kind of equivalent of

in Java? I have an exit in my code and would really like to be able to test it. The only thing I found in C# is a not really nice workaround.

Example Code

public void CheckRights()
{
if(!service.UserHasRights())
{
Environment.Exit(1);
}
}


Test Code

[TestMethod]
public void TestCheckRightsWithoutRights()
{
MyService service = ...
service.UserHasRights().Returns(false);

???
}


I am using the VS framework for testing (+ NSubstitute for mocking) but it is not a problem to switch to nunit or whatever for this test.

Answer

I ended up creating a new method which I can then mock in my tests.

Code

public void CheckRights()
{
    if(!service.UserHasRights())
    {
         Environment.Exit(1);
    }
}

internal virtual void Exit() 
{
    Environment.Exit(1);
}

Unit test

[TestMethod]
public void TestCheckRightsWithoutRights()
{
    MyService service = ...
    service.When(svc => svc.Exit()).DoNotCallBase();
    ...
    service.CheckRights();
    service.Received(1).Exit();
}