cbohannon cbohannon - 1 month ago 17
C# Question

NUnit Testing with Action and Lambda

I have been reading up on Actions and Lambda expressions on MSDN but there is still something I am missing. I have the following public class.

public class ExitChecker
{
public Action EnvironmentExitAction { get; set; }

public ExitChecker(string[] args)
{
if (string.Compare(args[0], "-help", true) == 0)
{
EnvironmentExitAction = () => Environment.Exit(0);
}
}
}


And I have the following test class.

[TestFixture]
public class AVSRunnerConsoleAppTests
{
[Test]
public void TestConsoleAppWithHelpArg()
{
string[] args = new string[1] { "-help" };
ExitChecker exitchecker = new ExitChecker(args);

bool exitZeroOccured = false;
exitchecker.EnvironmentExitAction = () => exitZeroOccured = true;

Assert.That(exitZeroOccured, Is.True);
}
}


I am attempting to test the Environment.Exit without actually calling the Environment.Exit. All seems to compile and run just fine but I can't seem to change the exitZeroOccured in the Lambda expression to true. Can someone point me in the right direction?

Answer

You're never invoking EnvironmentExitAction. Change your code to this:

[Test]
public void TestConsoleAppWithHelpArg()
{
    string[] args = new string[1] { "-help" };
    ExitChecker exitchecker = new ExitChecker(args);

    bool exitZeroOccured = false;
    exitchecker.EnvironmentExitAction = () => exitZeroOccured = true;

    exitchecker.EnvironmentExitAction.Invoke();

    Assert.That(exitZeroOccured, Is.True);
}
Comments