N单元中的C#测试异常

时间:2018-08-06 20:07:59

标签: c# unit-testing nunit

在下面的“默认”代码块中,我很难确定我的Assert语句应该如何测试异常和/或用户消息。有什么想法吗?

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

异常记录代码

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

1 个答案:

答案 0 :(得分:1)

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