无法使nunit测试异常工作。使用.net 2.0

时间:2011-07-21 08:03:08

标签: 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)
                {
                }
            }
        }

3 个答案:

答案 0 :(得分:0)

你抛出CustomerException但期望PersonException。并且您尝试匹配两个不同的字符串(“抛出”与“抛出”)。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

测试异常的另一种方法是在测试方法上使用ExpectedException属性。 IMO这更具可读性。一切都取决于什么对你有用。

[Test]
[ExpectedException(typeof(PersonException), ExpectedMessage = "Test person Exception thrown")]
public void When_calling_my_method_it_should_throw_an_exception()
{
    Person person=new Person();
    person.ThrowPersonException();
}