Dean Friedland
Dean Friedland

Reputation: 803

C# Testing Exceptions in N-Unit

I am having a hard time figuring out what my Assert statement should look like to test the Exception and/or the User Message in the "default" code block below. Any ideas?

public void LoadLanguage(string language)
        {
            switch (language)
            {
                case "Spanish":
                    ShouldPrintSpanish = true;
                    break;
                case "English":
                    ShouldPrintEnglish = true;
                    break;
                case "Both":
                    ShouldPrintSpanish = true;
                    ShouldPrintEnglish = true;
                    break;
                default:
                    string ex = "AgreementDetailViewModel.LoadFormsForSelectedLanguage() failed to execute correctly";
                    ExceptionLog.LogException(new Exception(ex),Environment.MachineName, null, "");
                    ShowError("User should have been able to select a language from the dropdown");
                    throw new Exception(ex);
            }
        }

Exception Logging Code

public static ExceptionLog LogException(Exception exception)
        {
            return new ExceptionLog(exception, "", "", "", "");
        }

private ExceptionLog (Exception exception, string environmentVariables, string computerName, string ipAddress, string createdBy)
        {
            if (exception == null)
                throw new ArgumentException("The exception cannot be null.");

            _Exception = exception;
            CreateAndSaveParentException(computerName, environmentVariables, ipAddress, createdBy);
            CreateAndSaveChildExceptions();         
        }

Upvotes: 0

Views: 48

Answers (1)

V0ldek
V0ldek

Reputation: 10623

Use Assert.Throws<ExceptionType>. https://github.com/nunit/docs/wiki/Assert.Throws

Upvotes: 1

Related Questions