c# - 无法使 nunit 测试异常起作用。使用 .net 2.0

标签 c# unit-testing

无论出于何种原因,我似乎无法获得正确的语法。 您如何进行以下测试。我只有一个简单的方法 TestThrowexception 并希望它通过 我在这里做错了什么?

           [TestFixture]
            public class ExceptionsTests
            {       
                [Test]
                public void When_calling_my_method_it_should_throw_an_exception()
                {
                //THIS DOES NOT WORK
                    Person person=new Person();

                    PersonException ex = Assert.Throws<PersonException>(delegate { person.ThrowPersonException(); },
                                                             Has.Property("Message").EqualTo("Test person Exception throw"));

                }
            }

            public class Person
            {
                public void ThrowException()
                {
                    throw new Exception("Test Exception thrown");
                }
                public void ThrowPersonException()
                {
                    throw new CustomerException("Test person Exception thrown");
                }


                public void ThrowArgumentException(string myParam)
                {
                    throw new ArgumentException("Argument Exception", myParam);
                }
            }
            [Serializable]
            public class PersonException : Exception
            {

                public PersonException()
                {
                }

                public PersonException(string message)
                    : base(message)
                {
                }

                public PersonException(string message, Exception inner)
                    : base(message, inner)
                {
                }

                protected PersonException(
                    SerializationInfo info,
                    StreamingContext context)
                    : base(info, context)
                {
                }
            }
        }

最佳答案

除了您抛出的异常类型的问题外,我会这样做。我认为它更具可读性。

[Test]
public void When_calling_my_method_it_should_throw_an_exception()
{
    Person person=new Person();
    PersonException ex = Assert.Throws<PersonException>(delegate { person.ThrowPersonException(); });
    Assert.That(ex.Message,Is.EqualTo("Test person Exception thrown");
}

关于c# - 无法使 nunit 测试异常起作用。使用 .net 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6772990/

相关文章:

c# - 使用 C# 将文本数据文件写入 Excel

typescript - 进行 Jest 测试以在抛出任何错误时失败?

wcf - "Fast"WCF服务的集成测试

c# - 我可以创建一个可以修改用户界面并且可以中止的线程吗?

c# - 按列表包含的对象的属性对自定义列表进行排序

c# - 将隐式类型的局部变量初始化为 IList

c# - 类型参数 'System.Net.Http.Headers.MediaTypeHeaderValue' 违反了类型参数 'T' 的约束

C# - 单元测试,模拟?

android - 如何模拟 BitmapFactory : Method decodeFile

IOS -XCTest : How Do I Get A Run Loop to Work in A Unit Test? 中的 NSRunLoop