简体   繁体   中英

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM